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); 
    });
    
    评论

报告相同问题?