Using the ajax() function provides the greatest functionality available for XMLHttpRequests.
jQuery also provides other higher-level abstractions for doing very specific
types of XMLHttpRequests. These functions are essentially shortcuts for the
ajax() method.
These shortcut methods are:
load()
get()
getJSON()
getScript()
post()
The point is that while the shortcuts can be nice at times, they all use ajax() "under
the hood".
When you want all the features and customizations that jQuery offers when it comes
to AJAX, then you should just use the ajax() method. A more commonly used acronym
for AJAX is XHR - short for XMLHttpRequest.
By default, the ajax() and load() AJAX functions both use the GET HTTP protocol.
jQuery support for cross-domain JSONP
JSON with Padding (JSONP) is a technique that allows the sender of an HTTP request,
where JSON is returned, to provide a name for a function in the client page that
is invoked with the JSON object as a parameter of the function. This technique
does not use XHR. It uses the script element so data can be pulled into any site,
from any site. The purpose is to circumvent the same-source policy limitations
of XMLHttpRequest.
Using the getJSON() jQuery function, you can load JSON data from another domain when
a JSONP callback function is added to the URL, provided that the supplier honors
JSONP requests.
&jsoncallback=? is what is appended to the url when using JSONP. Some APIs use
other names, such as "callback", so it's always a good idea to
check in advance by reading the vendor's documentation.
The ? value is used as a shortcut that tells jQuery to call the function that is
passed as a parameter of the getJSON() function. You could replace the ? with
the name of another function if you do not want to use this shortcut.
When using the ? shortcut jQuery will simply call the callback function you provided
in the getJSON() function. The parameter passed to this callback function is
the actual JSON data that was requested.
Prevent the browser from caching XHR requests
When doing an XHR request, Internet Explorer will cache the response. If the response
contains static content with a long shelf life, caching may be a good thing.
However, if the content being requested is dynamic and could change by the second,
you will want to make sure that the request is not cached by the browser. One
possible solution is to append a unique query string value to the end of the
URL. This will ensure that for each request the browser is requesting a unique
URL:
// Add unique query string at end of the URL.
url:'someurl?nocache='+(new Date()).getTime()
Another solution, which is a global solution, is to set up all AJAX requests by default
to contain the no-cache logic. To do this, use the ajaxSetup function to globally
switch off caching:
$.ajaxSetup({
cache: false // True by default. False means caching is off.
});
Now, in order to overwrite this global setting with individual XHR requests, you
simply change the cache option when using the ajax() function. Below is a coded
example of doing an XHR request using the ajax() function, which will overwrite
the global setting and cache the request:
$.ajaxSetup ({ cache: false // True by default. False means caching is off.
});
jQuery.ajax({ cache: true, url: 'someUrl', type: 'POST' } );
The most important $.ajax parameters are the following:
async A Boolean value indicating whether the request should be handled asynchronous or
not. Default is true
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages.
Default is true
complete(xhr,status) A function to run when the request is finished (after the success and error functions).
contentType The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context Specifies the "this" value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected from the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for
the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response
has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be
transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param
serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object
Here is a sample $.ajax call that uses some of these features:
<script type="text/javascript">
$(document).ready(function(){
$("form#formId").submit(function() {
inputField = $('#inputFieldId').attr('value');
$.ajax({
type: "POST",
url: "yourpage.aspx",
cache: false,
data: "inputField ="+ inputField,
success: function(html){
$("#ajax-results").html(html);
}
});
return false;
});
});
</script>
And here is an $.ajax call to an ASPX Page Method:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here with 'msg',which contains the returned data
}
});
There are so many things you can do with jQuery, it should be no suprise that Microsoft
has included it in both their standard ASP.NET and ASP.NET MVC application templates. A .vsdoc file is also provided, which supplies intellisense in the IDE editor.