如何重定向来自Ajax请求的响应重定向、Ajax

2023-09-10 19:52:36 作者:别装了她不爱你べ

我需要从响应重定向到一个页面。我做了一个Ajax调用,并能处理的成功。有html页面的响应,但如何将其重定向到该页面。 这是我的code。

  $(#launchId)。生活(点击,函数(){
    VAR ID = $(#ID)VAL()。
    VAR数据='ID ='+ ID;
    $阿贾克斯({
        网址:xyz.json
        类型:后,
        数据:数据,
        数据类型:JSON,
        完成:函数(响应){
             window.location.href =响应;
        }
    });
 });
 

解决方案

不使用AJAX将使它更容易些:

 <表单类型=POST行动=xyz.json>
    <标签=ID>输入ID:< /标签><输入ID =IDNAME =ID>
    <按钮类型=提交ID =launchId>发送和LT; /按钮>
< /形式GT;
 

如果你真的想使用Ajax,你应该生成一个不同的服务器响应,只包含要在您的网页或实际的JSON更新HTML部分。

Ajax

如果你坚持使用响应您目前得到的,和它打交道的适当方式将是的 文件撰写

  $。阿贾克斯({
    网址:xyz.json
    类型:后,
    数据:数据,
    数据类型:HTML,//这是没有JSON响应!
    成功:函数(响应){
         的document.write(响应); //覆盖当前文档
    },
    错误:函数(ERR){
         警报(ERR +确实发生了,请重试);
    }
});
 

I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page. Here's my code.

$("#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;                  
        }
    });
 });

解决方案

Not using ajax would make this easier:

<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>

If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.

If you insist on using the response which you currently get, the appropriate way of dealing with it would be 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");
    }
});