JQuery Ajax Instance Full parsing

Source: Internet
Author: User
Tags bind getscript html page http request json string format browser cache
JQuery Ajax Instance full parsing

jquery is really a very good lightweight JS framework that can help us to develop JS applications quickly and to some extent change the way we write JavaScript code.

Talk less, go straight to the point, we first look at some simple methods, these methods are to Jquery.ajax () encapsulation to facilitate our use of the method, of course, if you want to deal with complex logic, still need to use Jquery.ajax () (which will be said later).

1. Load (URL, [data], [callback]): Load the remote HTML file code and insert it into the DOM.

URL (String): The URL address of the requested HTML page.

Data (MAP): (optional parameter) sends the Key/value to the server.

Callback (callback): (optional parameter) callback function when the request is complete (does not need to be success).

This method is passed by default using GET, and is automatically converted to post if the [data] parameter is passed in. In JQuery 1.2, you can specify a selector to filter the loaded HTML document, and only the filtered HTML code will be inserted in the DOM. Syntax such as "URL #some > selector".

This method makes it easy to dynamically load some HTML files, such as forms.

Example code:

$ (". Ajax.load"). Load ("http://www.cnblogs.com/yeer/archive/2009/06/10/1500682.html. Post",
function (ResponseText, textstatus, XMLHttpRequest) {

alert (responsetext);//Request returned content //alert (textstatus);//Request Status: Success,error //alert (XMLHttpRequest);// XMLHttpRequest Object });

The results are displayed here.

Note: Do not know why URL write absolute path under FF will error, know the trouble to tell under. The Get () and post () examples below use an absolute path, so you will get an error under FF and you will not see the results returned. The Get () and post () examples are all cross-domain calls, and there is no way to get the results after the transmission, so the run button is removed.

2. Jquery.get (URL, [data], [callback]): Use Get method to make asynchronous request

Parameters:

URL (String): The URL address of the sending request.

Data (MAP): (optional) to be sent to the server, in the form of Key/value key-value pairs, which are appended to the request URL as querystring.

Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).

This is a simple GET request feature to replace complex $.ajax. The callback function can be called when the request succeeds. If you need to execute the function on error, use $.ajax. Example code:

$.get ("./ajax.aspx", {Action: "Get", Name: "Lulu"}, function (data, textstatus) {
The returned data can be xmldoc, jsonobj, HTML, text, and so on. This Here this point is the option configuration information for the AJAX request, please refer to the following image alert (data);
alert (textstatus);//Request Status: Success,error and so on.
Of course, the error is not caught here, because the error does not run the callback function at all //alert (this); });

Click Send Request:

The This in the Jquery.get () callback function points to the option configuration information for the AJAX request:

3. Jquery.post (URL, [data], [callback], [type]): Use post to make asynchronous requests

Parameters:

URL (String): The URL address of the sending request.

Data (MAP): (optional) to be sent to the server, in the form of Key/value key-value pairs.

Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).

Type (String): (optional) The official description is: Type of data to be sent. The type that should actually be requested for the client (Json,xml, etc.)

This is a simple POST request function to replace the complex $.ajax. The callback function can be called when the request succeeds. If you need to execute the function on error, use $.ajax. Example code:

Ajax.aspx:

Response.ContentType = "Application/json";
Response.Write ("{result: '" + request["Name"] + "hello. (The message comes from the server) '} ');
JQuery Code:
$.post ("Ajax.aspx", {Action: "Post", Name: "Lulu"},
function (data, textstatus) {
Data can be xmldoc, jsonobj, HTML, text, and so on. This For the option configuration information for this AJAX request, please refer to the This alert (Data.result) mentioned in Jquery.get ().
}, "JSON");

Click Submit:

The format of the request is "JSON":

If you set the request format to "JSON", at this point you do not have to set Response back ContentType: Response.ContentType = "Application/json"; Then you will not be able to capture the returned data.

Note that alert (data.result); Because the Accept header is set to "JSON", the data returned here is an object and does not need to be converted to an object using eval ().

4. Jquery.getscript (URL, [callback]): Request to load and execute a JavaScript file via GET mode. Parameters

URL (String): The JS file address to be loaded.

Callback (function): (optional) The post-load callback function is successfully loaded.

Before the JQuery 1.2 version, GetScript can only invoke the same domain JS file. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you join the script through GetScript, add the delay function.

This method can be used for example, when only the editor focus () to load the editor needs the JS file. Here are some sample code: Load and execute test.js.

JQuery Code:

$.getscript ("Test.js");

Load and execute ajaxevent.js, and display the information after success.

JQuery Code:

$.getscript ("Ajaxevent.js", function () {
Alert ("Ajaxevent.js loading is complete and execution is complete.) You can click the Get or Post button above to see what's different. ");
});

After loading, please re-click on the load request above to see what is different.

JQuery Ajax Events

Ajax requests generate a number of different events, and we can subscribe to these events and handle our logic in them. There are two types of Ajax events in jquery: Local events and global events.

A local event is defined within a method every time an AJAX request is requested, for example:

$.ajax ({
Beforesend:function () {
Handle the Beforesend event }, complete:function () {
Handle the Complete Event } //... });

The global event is triggered every time an AJAX request is made, it broadcasts to all elements in the DOM, and the script loaded in the GetScript () example above is the global Ajax event. Global events can be defined as follows:

$ ("#loading"). Bind ("Ajaxsend", function () {
$ (this). Show ();
}). bind ("Ajaxcomplete", function () {
$ (this). Hide ();
});

Or:

$ ("#loading"). Ajaxstart (function () {
$ (this). Show ();

We can disable global events on a specific request, as long as you set the global option:

$.ajax ({
URL: "Test.html",
global:false,//disables global Ajax events. // ... });

Here is the full list of Ajax events given by the jquery official: Ajaxstart (Global event)
This event was broadcast if an AJAX request was started and no other AJAX requests was currently running. Beforesend (Local Event)
This event, which was triggered before an Ajax request was started, allows you to modify the XMLHttpRequest object (setting Additional headers, if need be.) Ajaxsend (Global Event)
This global event is also triggered before, the request is run. Success (Local Event)
This event is a called if the request was successful (no errors from the server, no errors with the data). Ajaxsuccess (Global Event)
This event is also only called if the request was successful. Error (Local Event)
This event was only called if an error occurred with the request (you can never has both an error and a success callback W ith a request). Ajaxerror (Global Event)
This global event behaves the same as the local error event. Complete (Local Event)
This event is a called regardless of if the request was successful, or not. You'll always receive a complete callback, even for synchronous requests. Ajaxcomplete (Global Event)
This event behaves the same as the complete event and would be triggered every time an Ajax request finishes. Ajaxstop (Global Event)
This global event was triggered if there is no more Ajax requests being processed.

Refer to the API documentation for specific global events.
Well, here's how the most powerful Ajax request method in jquery is $.ajax ();

Jquery.ajax (options): Loading remote data over HTTP requests

This is the underlying AJAX implementation of jquery. Easy to use high-level implementation see $.get, $.post and so on.

$.ajax () returns the XMLHttpRequest object that it created. In most cases you do not need to manipulate the object directly, but in special cases you can use it to terminate the request manually.

Note: If you specify the DataType option, make sure that the server returns the correct MIME information (such as XML returns "Text/xml"). The wrong MIME type can cause unpredictable errors. See Specifying the Data Type for AJAX requests.
When you set the datatype type to ' script ', all the remote (not in the same domain) post requests are converted back to get mode.

$.ajax () has only one parameter: The parameter Key/value object, which contains the configuration and callback function information. Detailed parameter options are shown below.

In JQuery 1.2, you can load JSON data across domains and set the data type to JSONP when used. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function. When the data type is set to "Jsonp", JQuery automatically calls the callback function. (I don't quite understand that)

Parameter list:

Name of parameter Type Describe
Url String (Default: Current page address) sends the requested address.
Type String (Default: "Get") The Request method ("POST" or "get"), the default is "get". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it.
Timeout Number Sets the request time-out (in milliseconds). This setting overrides the global settings.
Async Boolean (default: TRUE) by default, all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the sync request will lock the browser, and the user's other actions must wait for the request to complete before it can be executed.
Beforesend Function You can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {
This The options for this AJAX request }
Cache Boolean (default: TRUE) JQuery 1.2 new feature, set to False will not load the request information from the browser cache.
Complete Function The callback function after the request completes (called when the request succeeds or fails). Parameters: XMLHttpRequest Object, Success information string.
function (XMLHttpRequest, textstatus) {
This The options for this AJAX request }
ContentType String (Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. The default values are suitable for most applications.
Data Object,
String
Data sent to the server. is automatically converted to the request string format. The GET request will be appended to the URL. View the ProcessData option description to disallow this automatic conversion. Must be a key/value format. If an array, JQuery automatically corresponds to the same name for the different values. such as {foo:["bar1", "Bar2"]} converted to ' &foo=bar1&foo=bar2 '.
DataType String

Expected data type returned by the server. If not specified, JQuery automatically returns Responsexml or ResponseText based on the HTTP packet MIME information and is passed as a callback function parameter, with the available values:

"XML": Returns an XML document that can be processed with jQuery.

HTML: Returns plain text HTML information, including the script element.

"Script": Returns plain text JavaScript code. Results are not automatically cached.

"JSON": Returns the JSON data.

"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.

Error Function (Default: This method is called when a request for automatic judgment (XML or HTML) fails.) This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being captured.
function (XMLHttpRequest, textstatus, Errorthrown) {
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.