Javascript 如何在 jQuery $.get/ajax 请求中获取请求 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3828104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:18:00  来源:igfitidea点击:

How to get request url in a jQuery $.get/ajax request

javascriptjquery

提问by Christopher

I have the following code:

我有以下代码:

$.get('http://www.example.org', {a:1,b:2,c:3}, function(xml) {}, 'xml');

Is there a way to fetch the url used to make the request after the request has been made (in the callback or otherwise)?

有没有办法在发出请求后(在回调中或以其他方式)获取用于发出请求的 url?

I want the output:

我想要输出:

http://www.example.org?a=1&b=2&c=3

回答by Reigel

I can't get it to work on $.get()because it has no completeevent.

我无法让它工作,$.get()因为它没有complete事件。

I suggest to use $.ajax()like this,

我建议这样使用$.ajax()

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

疯狂的演示

回答by suluke

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's contextoption, as stated in the documentation:

由于 jQuery.get 只是 jQuery.ajax 的简写,另一种方法是使用后者的context选项,如文档中所述:

The thisreference within all callbacks is the object in the context option passed to $.ajaxin the settings; if context is not specified, this is a reference to the Ajax settings themselves.

this所有回调中的引用是传递给$.ajax设置中的上下文选项中的对象;如果未指定上下文,则这是对 Ajax 设置本身的引用。

So you would use

所以你会使用

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});