weixin_33705053 2017-09-19 13:27 采纳率: 0%
浏览 71

变量在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
    });
}

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 ?

  • 写回答

2条回答 默认 最新

  • H_MZ 2017-09-19 13:30
    关注

    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.

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

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog