开发者

Get params of jQuery AJAX request on complete

开发者 https://www.devze.com 2023-02-04 22:14 出处:网络
How can I find out what parameters were passed to an (asynchronous) jQuery AJAX request after it is complete?

How can I find out what parameters were passed to an (asynchronous) jQuery AJAX request after it is complete?

Basically, I am firing a bunch of AJAX requests with different id passed as a parameter and displaying the results to the user when each of them finishes. Now, if the request is successful, I can pass the id back in the result of the req开发者_如何学运维uest. But, if the request fails, I don't know which request failed, i.e. for what id was that request.

Example (javascript/jQuery):

for(var i=0; i < 10; i++ ) {

    $.ajax({
        type: "GET",
        url: "get-results.php", 
        data: { 'id': i },
        success: function(data, textStatus, xmlReq) {

            data = $.parseJSON(data);
            $("#result" + data.id).html(data.result);

        },
        error: function(xmlReq, textStatus, errorThrown) {

            var id= ???;
            $("#result" + id).html('error bla bla');

        }
   });
}


$.ajaxError gives you the data send via the AJAX call.

.ajaxError(handler(event, XMLHttpRequest, ajaxOptions, thrownError))

The ajaxOptions object contains all the options that can be set via $.ajax

So, instead of using the error: option in $.ajax, use $.ajaxError.

$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError){
  if(ajaxOptions.url.indexOf('get-results.php') != -1){
    var data = ajaxOptions.data; // this is a string: 'id=1&param2=4'
                                 // to get the ID, you need to parse this
  }
});


You need to capture the current value of i for the error function. And you capture with a closure. So:

error: function(id) {
    return function(xmlReq, textStatus, errorThrown) {

        $("#result" + id).html('error bla bla');

    };
}(i)

That is error is the result of immediately calling an anonymous function passing in the current value of i.


Use the fact that Javascript supports closures, and just write the variable name (but be careful to copy it inside the for block scope so that it does not change):

for(var i=0; i < 10; i++ ) {
    var INDEX = i;
    $.ajax({
        type: "GET",
        url: "get-results.php", 
        data: { 'id': i },
        success: function(data, textStatus, xmlReq) {

            data = $.parseJSON(data);
            $("#result" + data.id).html(data.result);

        },
        error: function(xmlReq, textStatus, errorThrown) {

            var id = INDEX;
            $("#result" + id).html('error bla bla');

        }
   });
}

I believe that this is what you want.


You'll need to pass them back with your response.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号