如何从ajax请求重定向响应
How to redirect response from ajax request
我需要从响应重定向到一个页面。我做了一个ajax调用,可以处理成功。有一个html页面响应,但如何重定向到该页。
这是我的代码。
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
不使用ajax会使这更容易:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
如果您真的想使用ajax,您应该生成一个不同的服务器响应,只包含您想要在页面中更新的HTML部分或实际的JSON。
如果您坚持使用当前得到的响应,则处理它的适当方法是document.write
:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
请尝试一下。
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
您的响应是一个对象,包含responseText
属性中页面的完整HTML。
你可以用$(body).html(response.responseText);
代替window.location.href = ...;
,用你得到的响应覆盖当前页面的内容。
...
complete : function(response) {
$(body).html(response.responseText);
}
但我建议你不要这样做,否则可能会与页面上已有的样式和其他冲突。
在你的HTML中添加一个id为" content "的div,就像这样
<div id='content'/>
由于您的响应是html在您的完整功能追加内容到div像这样-
complete : function(response) {
$('#content').append(response.responseText);
}
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});
相关文章:
- 将对Ajax PUT的json响应重定向到要由EL解析的JSP中
- 在Ajax响应后使用window.location.replaces不会立即重定向
- 重定向到json响应中的url
- 使用响应重定向退出弹出窗口
- AngularJs $http postsuccessCallback 导致页面重定向,即使服务器以 200 状态响应也
- CakePHP 3 Json 响应而不是重定向(如果 ext = json )
- 在 aspx 页上输入触发响应的键.重定向
- HTTP 200 + 空响应 + 重定向
- XMLHttpRequest 无法加载 [url].预检响应无效(重定向)
- 重定向到新页面作为对 XHR 发布请求的响应
- 当响应 JSON 对象数据计数为零时,AJAX 成功回调函数重定向到错误回调
- 如何在会话过期时从 ajax 响应自动重定向网页
- 单击后响应重定向到路由器 URL 并显示默认页面
- rails重定向到格式化html在js中发送响应
- 如何在响应重定向到成功网址后完成活动 Payu paymentgetway 与安卓.
- 响应.重定向和javascript ajax调用
- 如何在node.js中处理带有身份验证的重定向响应
- 如何从ajax请求重定向响应
- 将HTTP请求发送到第三方服务器并获得重定向响应
- jQuery Ajax和重定向响应从服务器