3

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

5 回答 5

3

请试试这个。

var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
于 2013-06-01T09:48:30.627 回答
3

不使用 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");
    }
});
于 2013-06-01T09:56:49.287 回答
1

您的响应是一个对象,其中包含responseText属性中页面的完整 HTML。

您可能可以这样做,$(body).html(response.responseText);而不是window.location.href = ...;用您得到的响应覆盖当前页面内容。

...
complete : function(response) {
    $(body).html(response.responseText);
}

但我建议您不要这样做,并且可能与页面上已有的内容存在风格和其他冲突。

于 2013-06-01T09:46:11.367 回答
0

在您的 HTML 中添加一个 id 为“内容”的 div,如下所示

<div id='content'/>

由于您的响应是完整函数中的 html,因此将内容附加到 div 中,如下所示 -

 complete : function(response) {
         $('#content').append(response.responseText);
    }

如果您仍然遇到问题,请告诉我。

于 2013-06-01T09:46:42.980 回答
-2

尝试这个

$("#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;                  
        }
    });
 });
于 2013-06-01T09:40:52.937 回答