如何从ajax请求重定向响应

How to redirect response from ajax request

本文关键字:重定向 响应 请求 ajax      更新时间:2023-09-26

我需要从响应重定向到一个页面。我做了一个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;                  
        }
    });
 });