jQuery: get url in success function

2020-03-17 03:35发布

I would like to get the url from a jQuery success function, after it retreives data from the server. Unfortunately, the three parameters the success function takes don't expose the original url:

success: function(data, statusText, jqhxr)

I dumped the jqhxr variable, and couldn't find the url in there. The reason I need the url is because I'm making several calls at once through a loop, and therefore I have no idea which Ajax call is coming back. Making it an asynchronous call didn't help either.

Thank you in advance!

标签: jquery ajax
4条回答
▲ chillily
2楼-- · 2020-03-17 04:17

You could probably use context when making the ajax call.

$.ajax({
  url: "test1.html",
  context: $("#call1")
});

$.ajax({
  url: "test2.html",
  context: $("#call2")
});

<div id="call1" class="hidden" data-url="whatever1"></div>
<div id="call2" class="hidden" data-url="whatever2"></div>

then in

success: function(data, statusText, jqhxr) {
    var url = $(this).data("url");
}

That way you could get any data, not just the url. Put any data you want to access in the corresponding div element.

查看更多
Juvenile、少年°
3楼-- · 2020-03-17 04:25

you mean making it a synchronous call didn't help...?

and my suggestion would be to set a parameter in the data you're getting back to determine what to do with it, if you're looping through a bunch of AJAX calls. But really you should have to loop through more than one call if you're doing it right you should be able to send enough parameters along with the data to get it all back in one call, this reduces the number trips between client and server, server and database, then server back to client.

查看更多
Melony?
4楼-- · 2020-03-17 04:34

If you call the server script via jQuery .ajax() or .post() or .get(), then you must have the url available in the success callback function, even if you are using a loop. That is because you have to pass the url to all three of those methods, and the result returned is specific to the url that you pass.

For example:

for(var i=0; i<10; i++) {
    url = "action_remote_" + i + ".php";
    $.ajax({
        type:'POST',
        url: url,
        data:$('#' + str_form_id).serialize(),
        success: function(response) {
            alert(url);
        }
    });
}

Unless I am not understanding you correctly...

查看更多
聊天终结者
5楼-- · 2020-03-17 04:36

this.url inside success function will work because this refers to the current context of the function, and since the success function is part of the settings object that you're passing to .ajax() it will access the url property.

See an article describing js scope and .ajax().

查看更多
登录 后发表回答