JQuery Ajax Full parsing _jquery

Source: Internet
Author: User
Tags bind error handling getscript string format browser cache
jquery is really a nice lightweight JS framework that can help us quickly develop JS applications and, to some extent, change our habit of writing JavaScript code.
Cut the crap, go straight to the point, let's take a look at some simple methods that encapsulate the Jquery.ajax () to make it easier for us to use, and of course, if you want to deal with complex logic, you need to use Jquery.ajax ().
1. Load (URL, [data], [callback]): Loads the remote HTML file code and inserts it into the DOM.
URL (String): The URL address of the requested HTML page.
Data (MAP): (optional parameters) sent to the server's key/value.
Callback (callback): (optional parameter) a callback function that does not need to be success when the request completes.
This method is passed by default using Get method, 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 into the DOM. Syntax is like "URL #some > selector".
This method makes it easy to dynamically load some HTML files, such as forms.
Sample code:
Copy Code code as follows:

$ (". Ajax.load"). Load ("http://www.cnblogs.com/QLeelulu/archive/2008/03/30/1130270.html. Post",
function (ResponseText, textstatus, XMLHttpRequest) {
this;//here. This point is the current DOM object, that is $ (". Ajax.load") [0]
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 the URL write absolute path under FF will be wrong, know the trouble to tell. The following get () and post () examples use an absolute path, so you will go wrong under FF and you will not see the results returned. The Get () and post () examples are called across domains, and they are found to be not able to get results, so the run button is removed.
2. Jquery.get (URL, [data], [callback]): Asynchronous request using Get method
Parameters:
URL (String): The URL address where the request is sent.
Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair, is appended to the request URL as querystring.
Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.
This is a simple GET request function to replace the complex $.ajax. Callback functions can be invoked when the request succeeds. If you need to perform 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 is the option configuration information for the AJAX request, please refer to the following figure
alert (data);
Alert (Textstatus),//Request status: Success,error, and so on. Of course, the error is not captured here, because the callback function is not run at all when the error
alert (this);
); Click Send Request:
This in the Jquery.get () callback function points to the option configuration information for the AJAX request:

3. Jquery.post (URL, [data], [callback], [Type]): Asynchronous request using POST method
Parameters:
URL (String): The URL address where the request is sent.
Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair.
Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.
Type (String): (optional) The official description is: type of data to is 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. Callback functions can be invoked when the request succeeds. If you need to perform 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 server) '} '); JQuery code:
$.post ("Ajax.aspx", {Action: "Post", Name: "Lulu"},
function (data, textstatus) {
Data can be xmldoc, jsonobj, HTML, text, and so on.
This This AJAX request option configuration information, please refer to Jquery.get ().
alert (Data.result);
}, "JSON"; Click Submit:
This sets the requested format to "JSON":

If you set the requested format to "JSON", you are not setting the Response back ContentType as: Response.ContentType = "Application/json"; Then you will not be able to capture the returned data.
Note that alert (data.result); With the Accept header "JSON" set, the data returned here is an object that does not need to be converted to an object with eval ().
4. Jquery.getscript (URL, [callback]): Load and execute a JavaScript file with a Get-mode request.
Parameters
URL (String): The JS file address is to be loaded.
Callback (function): (optional) After successfully loading the callback function.
Before the JQuery 1.2 version, Getscript can only invoke the same domain JS file. 1.2, you can invoke JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script by getscript, add the delay function.
This method can be used for example, when only the editor focus () to load the editor required JS file. Here are some sample code:
Load and execute test.js.
JQuery Code:
$.getscript ("Test.js");
--------------------------------------------------------------------------------
Load and execute ajaxevent.js, and then display the information successfully.
JQuery Code:
$.getscript ("Ajaxevent.js", function () {
Alert ("Ajaxevent.js load complete and execution completed.) What's the difference if you click the Get or Post button above? ");
});
After loading, please click on the load request above to see what the difference is.
JQuery Ajax Events
Ajax requests produce a number of different events, and we can subscribe to these events and process our logic in them. There are two kinds of Ajax events in jquery: Local events and global events.
A local event is defined within a method at each AJAX request, for example:
$.ajax ({
Beforesend:function () {
Handle the Beforesend Event
},
Complete:function () {
Handle the Complete event
}
// ...
The global event is triggered by every Ajax request, and it broadcasts to all elements in the DOM, and the script loaded in the Getscript () example above 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 at a specific request, as long as you set the global option:
$.ajax ({
URL: "Test.html",
global:false,//disables global Ajax events.
// ...
The following is a complete list of Ajax events given by the jquery official:
Ajaxstart (Global Event)
This event is broadcast if a AJAX request is started and no other AJAX requests are currently running.
Beforesend (local Event)
This event, which are triggered before an Ajax request is started, allows your to modify the XMLHttpRequest object (setting Additional headers, if need be.)
Ajaxsend (Global Event)
This global event was 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 and no errors with the data).
Ajaxsuccess (Global Event)
This event is also only called if the request was successful.
Error (Local Event)
This is the ' only called if ' occurred with the ' request (you can never have 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 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 of Ajax request finishes.
Ajaxstop (Global Event)
This global event are triggered if there are no more Ajax requests being processed.
For specific global events, refer to the API documentation.
OK, here's what I'll say. The most powerful Ajax request method in jquery is $.ajax ();
Jquery.ajax (options): Load remote Data via HTTP request
This is the underlying AJAX implementation of jquery. Simple and easy-to-use high-level implementation see $.get, $.post, etc.
$.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 manually terminate the request.
Note: If you specify the DataType option, make sure that the server returns the correct MIME information (such as the XML return "Text/xml"). The wrong MIME type can cause unpredictable errors. See Specifying the Data Type for AJAX Requests.
When you set the DataType type ' script ', all 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 see below.
In JQuery 1.2, you can load JSON data across domains and use it to set the data type to JSONP. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function. When the data type is set to "Jsonp", JQuery automatically invokes the callback function. (I don't know this very well)
Parameter list:
Name Type Describe
Url String (Default: Current page address) sends the requested address.
Type String (Default: "Get") Request method ("POST" or "get"), default to "get". Note: Other HTTP request methods, such as put and DELETE, are also available, but only partially supported by browsers.
Timeout Number Sets the request timeout (in milliseconds). This setting overrides the global setting.
Async Boolean (Default: TRUE) The default setting is that all requests are asynchronous requests. If you need to send a sync request, set this option to false. Note that the synchronization 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) {
 //The options for this AJAX request}
Cache Boolean (default: TRUE) JQuery 1.2 new functionality, set to false will not load request information from the browser cache.
Complete Function The callback function (called when the request succeeds or fails) after the request completes. Parameters: XMLHttpRequest Object, Success message string.
function (XMLHttpRequest, textstatus) {
 //The options for this AJAX request}
ContentType String (Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. Default values are appropriate for most applications.
Data Object,
String
Data sent to the server. is automatically converted to the request string format. The GET request is appended to the URL. View the ProcessData option description to prevent this automatic conversion. Must be in the Key/value format. If you are an array, JQuery will automatically correspond to the same name for different values. such as {foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2 '.
DataType String

The type of data expected to be returned by the server. If not specified, JQuery will automatically return Responsexml or responsetext based on the HTTP packet MIME information and pass as a callback function parameter, available values:

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

HTML: Returns plain text HTML information, including script elements.

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

"JSON": Returns JSON data.

"Jsonp": jsonp format. when calling a function using JSONP form, such as "myurl?callback=?" JQuery will automatically replace it with the correct function name to execute the callback function.

Error Function (Default: Automatic judgment (XML or HTML)) This method is called when a request fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being caught.
function (XMLHttpRequest, textstatus, Errorthrown) {
 //typically Textstatus and Errorthown only one of them has a value //The Options for this Ajax request} 
Global Boolean (default: TRUE) triggers a global AJAX event. Setting to FALSE will not trigger global AJAX events, such as Ajaxstart or Ajaxstop. Can be used to control different AJAX events
Ifmodified Boolean (default: false) gets new data only when the server data changes. Use HTTP packet last-modified header information to determine.
ProcessData Boolean (default: TRUE) by default, the data sent is converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert.
Success Function callback function after successful request. This method has two parameters: the server returns the data, returns the status
function (data, textstatus) {
 //The options for this AJAX request}
Here are a few Ajax event parameters: Beforesend, Success, complete, error. We can define these events to deal well with each of our AJAX requests. Notice that this in these AJAX events is the information about the options for the Ajax request (refer to the picture of this when you say Get () method).
Read the argument list carefully, and if you want to use jquery for AJAX development, you need to be familiar with these parameters.
Sample code to get the title of the article on the home page of the blog:
$.ajax ({
Type: "Get",
URL: "Http://www.cnblogs.com/rss",
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 () {
Request Error Handling
}
});
A list of the first articles is displayed here.


Other
Jquery.ajaxsetup (Options): Sets the global AJAX default option.
Set AJAX request default address is "/xmlhttp/", prohibit triggering global Ajax event, use POST instead of default get method. Subsequent AJAX requests no longer have any option parameters set.
JQuery Code:
$.ajaxsetup ({
URL: "/xmlhttp/",
Global:false,
Type: "POST"
});
$.ajax ({data:mydata});
Serialize () and Serializearray ()
Serialize (): Sequence table table contents are strings.
Serializearray (): Serializes the Table element (similar to the '. Serialize () ' method) to return the JSON data structure.
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>

Serializearray () The result is:


Some resources

A jquery Ajax form form plugin:http://www.malsup.com/jquery/form/

A dedicated site to generate loading pictures:http://ajaxload.info/people think those loading more dazzling can be here to get some sun, convenient for everyone to take use, quack

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.