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
How to get request url in a jQuery $.get/ajax request
提问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 complete
event.
我无法让它工作,$.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 context
option, as stated in the documentation:
由于 jQuery.get 只是 jQuery.ajax 的简写,另一种方法是使用后者的context
选项,如文档中所述:
The
this
reference within all callbacks is the object in the context option passed to$.ajax
in 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});