Full Analysis of jquery + ajax instances

Source: Internet
Author: User
Tags getscript

JQuery is indeed a very lightweight JS framework that can help us quickly develop JS applications and change the habit of writing JavaScript code to a certain extent.

Let's talk nonsense and go straight to the question. Let's take a look at some simple methods, all of which are for jQuery. ajax () is encapsulated to facilitate our use of the method. Of course, if you want to process complicated logic, you still need to use jQuery. ajax () (this will be mentioned later ).

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

Url (String): the URL of the requested HTML page.

Data (Map): (optional) key/value data sent to the server.

Callback (Callback): (optional) callback function when the request is completed (success is not required.

By default, this method uses the GET method to pass data. If the [data] parameter passes data in, it is automatically converted to the POST method. In jQuery 1.2, you can specify a selector to filter loaded HTML documents. In DOM, only filtered HTML code is inserted. The syntax is like "url # some> selector ".

This method can easily dynamically load HTML files, such as forms.

Sample Code:

$ (". Ajax. load"). load ("http://www.cnblogs.com/yeer/archive/2009/06/10/1500682.html. post ",

Function (responseText, textStatus, XMLHttpRequest ){

This; // here this points to the current DOM object, that is, $ (". ajax. load") [0]

// Alert (responseText); // content returned by the request
// Alert (textStatus); // Request status: success, error
// Alert (XMLHttpRequest); // XMLHttpRequest object
});
The result is displayed here.
 

Note: I don't know why an error occurs when the absolute URL write path is in FF. please let us know. The following get () and post () Examples use absolute paths, so you will encounter errors in FF and will not see the returned results. The get () and post () Examples are all cross-origin calls, and the results cannot be obtained after being uploaded. Therefore, the run button is removed.

 

2. jQuery. get (url, [data], [callback]): Use the GET Method for asynchronous requests.

Parameters:

Url (String): the URL of the request.

Data (Map): (optional) data to be sent to the server, which is expressed in Key/value pairs and will be appended to the request URL as QueryString.

Callback (Function): (optional) callback Function when the load is successful (this method is called only when the Response returns success ).

This is a simple GET request function to replace complex $. ajax. You can call the callback function when the request is successful. To execute a function when an error occurs, use $. ajax. Sample 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 points to the options configuration of the Ajax request. For more information, see
Alert (data );

// Alert (textStatus); // Request status: success, error, and so on.

Of course, no error is caught here, because the callback function will not be run during the error process.
// Alert (this );
});
Click Send request:

This in the jQuery. get () callback function points to the option configuration information of the Ajax request:

 

 

3. jQuery. post (url, [data], [callback], [type]): Use the POST method for asynchronous requests.

Parameters:

Url (String): the URL of the request.

Data (Map): (optional) data to be sent to the server, expressed in Key/value pairs.

Callback (Function): (optional) callback Function when the load is successful (this method is called only when the Response returns success ).

Type (String): (optional) the official description is: Type of data to be sent. In fact, it should be the client request type (JSON, XML, and so on)

This is a simple POST Request function to replace complex $. ajax. You can call the callback function when the request is successful. To execute a function when an error occurs, use $. ajax. Sample Code:

Ajax. aspx:

Response. ContentType = "application/json ";

Response. Write ("{result: '" + Request ["Name"] + ", hello! (This 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; // configure the options of this Ajax request. For details, refer to this mentioned in jQuery. get ().
Alert (data. result );

}, "Json ");
Click to submit:

The request format is set to "json ":

 

If you set the request format to "json", you have not set the ContentType returned by Response to: Response. contentType = "application/json"; then you cannot capture the returned data.

Note that alert (data. result); because the Accept header is set to "json", the returned data 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 in GET mode.

Parameters
Url (String): the url of the JS file to be loaded.

Callback (Function): (optional) callback Function after successful loading.

Before jQuery 1.2, getScript can only call JS files in the same domain. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier versions cannot execute scripts simultaneously in the global scope. If you use getScript to add a script, add the latency function.

This method can be used, for example, to load the JS file required by the editor only when the editor focus (). See some sample code below:

Load and execute test. js.
JQuery code:

$. GetScript ("test. js ");

Load and execute AjaxEvent. js. The information is displayed after successful execution.

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 is different? ");

});
After loading, click the Load request above to see what is different.

JQuery Ajax events

Ajax requests Generate several different events. We can subscribe to these events and process our logic in them. There are two types of Ajax events in jQuery: local events and global events.

Partial events are defined in the method for each Ajax request. For example:

$. Ajax ({

BeforeSend: function (){

// Handle the beforeSend event
},
Complete: function (){

// Handle the complete event
}
//...
});
A global event is triggered by every Ajax request. It broadcasts all the elements in the DOM. The script loaded in the preceding getScript () example is a 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 in a specific request, as long as the global option is set:

$. Ajax ({

Url: "test.html ",

Global: false, // disable global Ajax events.
//...
});
The following is a complete list of Ajax events officially provided by jQuery:

AjaxStart (Global Event)
This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
BeforeSend (Local Event)
This event, which is triggered before an Ajax request is 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 only 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 is only called if an error occurred with the request (you can never have both an error and a success callback with a request ).
AjaxError (Global Event)
This global event behaves the same as the local error event.
Complete (Local Event)
This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
AjaxComplete (Global Event)
This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
AjaxStop (Global Event)
This global event is triggered if there are no more Ajax requests being processed.
For details about global events, refer to the API documentation.
Well, let's start with jQuery's most powerful Ajax Request Method $. ajax ();

 

JQuery. ajax (options): loads remote data through HTTP requests

This is the underlying AJAX Implementation of jQuery. For easy-to-use high-level implementation, see $. get, $. post, and so on.

$. Ajax () returns the created XMLHttpRequest object. In most cases, you do not need to directly operate on this object, but in special cases it can be used to manually terminate the request.

Note: If you specify the ype option, make sure that the server returns the correct MIME information (for example, xml returns "text/xml "). Incorrect MIME types may cause unpredictable errors. See Specifying the Data Type for AJAX Requests.
When the datatype type is set to 'script', all remote (not in the same domain) POST requests are switched to GET.

$. Ajax () has only one parameter: The parameter key/value object, which contains information about various configurations and callback functions. For detailed Parameter options, see.

In jQuery 1.2, you can load JSON data across domains. You need to set the data type to JSONP during use. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For 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 this)

Parameter List:

Parameter Name type description
Url String (default: Current page address) the address of the request sent.
Type String (default: "GET") Request Method ("POST" or "GET"), default: "GET ". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but are only supported by some browsers.
Timeout Number sets the request timeout (in milliseconds ). This setting overwrites the global setting.
Async Boolean (default: true) All requests are asynchronous requests by default. To send a synchronization request, set this option to false. Note: The synchronous request locks the browser. Other operations can be performed only after the request is completed.
Before sending a request, the beforeSend Function can modify the Function of the XMLHttpRequest object, for example, adding a custom HTTP header. The XMLHttpRequest object is a unique parameter.
Function (XMLHttpRequest ){

This; // the options for this ajax request
}
Cache Boolean (default: true) New jQuery 1.2 function. setting this parameter to false will not load request information from the browser cache.
The callback Function after the complete Function request is complete (called when the request is successful or fails ). Parameter: XMLHttpRequest object, success information string.
Function (XMLHttpRequest, textStatus ){

This; // the options for this ajax request
}
ContentType String (default: "application/x-www-form-urlencoded") Content Encoding type when sending information to the server. The default value is applicable to most applications.
Data Object,
String data sent to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL. View the description of the processData option to disable automatic conversion. It must be in Key/Value format. If it is an array, jQuery automatically corresponds to the same name for different values. For example, {foo: ["bar1", "bar2"]} is converted to '& foo = bar1 & foo = bar2 '.
DataType String
Expected data type returned by the server. If this parameter is not specified, jQuery will automatically return responseXML or responseText Based on the MIME information of the HTTP package and pass it as a callback function parameter. Available values:

"Xml": returns an XML document, which can be processed by jQuery.

"Html": returns plain text HTML information, including script elements.

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

"Json": Return JSON data.

"Jsonp": JSONP format. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function.

This method is called when an error Function (default: Automatic judgment (xml or html) request fails. This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object.
Function (XMLHttpRequest, textStatus, errorThrown ){

// Generally, textStatus and errorThown have only one value.
This; // the options for this ajax request
}
Whether global Boolean (default: true) triggers a global AJAX event. Setting false does not trigger global AJAX events, such as ajaxStart or ajaxStop. Can be used to control different Ajax events
IfModified Boolean (default: false) obtains new data only when the server data changes. Use the Last-Modified header information of the HTTP packet to determine.
ProcessData Boolean (default: true) by default, data sent is converted to an object (technically not a string) with the default content type "application/x-www-form-urlencoded ". If you want to send the DOM tree information or other information that does not want to be converted, set it to false.
Callback Function after successful success Function request. This method has two parameters: the server returns data and returns the status.
Function (data, textStatus ){

// Data cocould be xmlDoc, jsonObj, html, text, etc...
This; // the options for this ajax request
}
There are several Ajax event parameters: beforeSend, success, complete, and error. We can define these events to process every Ajax request. Note that this in these Ajax events points to the option Information of the Ajax request (see the image of this in the get () method ).
Read the parameter list carefully. If you want to use jQuery for Ajax development, you must be familiar with these parameters.

Sample Code to obtain the topic of the blog homepage:
$. Ajax ({

Type: "get ",

Url: "www.2cto.com ",

BeforeSend: function (XMLHttpRequest ){

// ShowLoading ();
},
Success: function (data, textStatus ){

$ (". Ajax. ajaxResult" ).html ("");

$ ("Item", data). each (function (I, domEle ){

$ (". Ajax. ajaxResult "). append ("<li>" + $ (domEle ). children ("title "). text () + "</li> ");

});

},

Complete: function (XMLHttpRequest, textStatus ){

// HideLoading ();
},
Error: function (){

// Handle request errors
}
});
The homepage article list is displayed.

 

 

Others

JQuery. ajaxSetup (options): sets the global AJAX default options.

Set the default address of an AJAX request to "/xmlhttp/". Do not trigger a global AJAX event. Use POST instead of the default GET method. No option parameters are set for subsequent AJAX requests.

JQuery code:

$. AjaxSetup ({

Url: "/xmlhttp /",

Global: false,

Type: "POST"

});

$. Ajax ({data: myData });
 

Serialize () and serializeArray ()

Serialize (): the content of the sequence table is a string.

SerializeArray (): serialize table elements (similar to the '. serialize ()' method) to return JSON data structure data.

Example:

HTML code:

<P id = "results"> <B> Results: </B> </p>
<Form>
<Select name = "single">
<Option> Single </option>
<Option> Single2 </option>
</Select>
<Select name = "multiple" multiple = "multiple">
<Option selected = "selected"> Multiple </option>
<Option> Multiple2 </option>
<Option selected = "selected"> Multiple3 </option>
</Select> <br/>
<Input type = "checkbox" name = "check" value = "check1"/> check1

<Input type = "checkbox" name = "check" value = "check2"

 

Checked = "checked"/> check2

<Input type = "radio" name = "radio" value = "radio1"

 

Checked = "checked"/> radio1

<Input type = "radio" name = "radio" value = "radio2"/> radio2

 

</Form>


The result of serializeArray () is:

 
Author: yj_021219

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.