Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

I want the output:

http://www.example.org?a=1&b=2&c=3 
like image 251
Christopher Avatar asked Sep 30 '10 05:09

Christopher


People also ask

What is URL in jQuery AJAX?

The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .

Can we use get in AJAX?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.


2 Answers

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

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

$.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

like image 114
Reigel Avatar answered Oct 02 '22 12:10

Reigel


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:

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.

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}); 
like image 31
suluke Avatar answered Oct 02 '22 12:10

suluke