变量在ajax请求中丢失 [英] Variable lost in ajax request

查看:131
本文介绍了变量在ajax请求中丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试将变量作为参数传递给嵌套的ajax请求回调时,我遇到一个奇怪的行为:

I'm facing a strange behaviour when trying to pass a variable as parameter to a nested ajax request callback:

$('form').on('submit',function(e){
    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    })
    e.preventDefault(e);
    $.ajax({
        type:"POST",
        url:dest_url,
        data:$(this).serialize(),
        dataType: 'json',
        success: function(data){
            if($.isEmptyObject(data.error)){
                // performing some actions
                // at this point, data.id contains my id

                // We call an other function, 
                // which performs an other ajax request, 
                // with data.id as parameter

                listRefresh(data.id);

            }else{
                // error message
            }
        },
        error: function(data){
            // error message
        }
    })
});


function listRefresh(id){
    console.log(id); // At this point, id contains my id
    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    })
    var src_url = location.href + '?id='+id;
    $.ajax({
        url: location.href,
        type: 'GET',
        cache: false
    })
    .done(function(id) {
        console.log(id); 

        // At this point the console outputs 
        // all my html code in place of id

        // I tried to pass data, response, id, but still the same issue
    })
    .fail(function() {
        //error message
    });
}

正如上面的代码注释中所述,在listRefresh ajax完成的回调中,我的变量似乎消失了,console.log在控制台中输出了我的整个html代码... 我从未见过这样的事情.您是否有原因的解释,以及如何将我的id作为参数传递给ajax回调?

As said in code comments above, in the listRefresh ajax done callback, my variable seems to disapear and the console.log outputs my entire html code in the console... I've never seen something like this. Do you have an explanation of why, and how could I pass my id as parameter to the ajax callback ?

推荐答案

.done()方法的参数是AJAX调用的响应.如果您的呼叫返回了HTML页面,则id变量将获得分配给它的所有html字符串.

The parameter of the .done() method is the response of the AJAX call. If your call returned a HTML page, the id variable got all of the html string assigned to it.

要将id保留在其变量中,只需使用另一个变量,如:

To keep the id in its variable simply use another one like:

.done(function(data) {
  console.log(data)
  console.log(id); 
});

这篇关于变量在ajax请求中丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆