Jquery. Ajax is the underlying Ajax operation method encapsulated by jquery. At the same time, jquery also provides several frequently used high-level packages, such as jquery. Get and jquery. Post. The following is a summary of several common usage methods of jquery. Ajax based on my understanding and usage in my work. The record is only used for memo. Due to limited horizontal capabilities, the shortcomings or errors in this article should be pointed out by the masses.
Before using the jquery. Ajax method, we must first understand its parameter definitions. Jquery. Ajax has a lot of optional parameters, here only a brief introduction of my work commonly used (for more parameter introduction see http://api.jquery.com/jQuery.ajax ):
Parameter Name |
Parameter type |
Default Value |
Description |
Type |
String |
"Get" |
Request Method ("get" or "Post", you can also use "put"/"delete", but only supported by some browsers) |
URL |
String |
Current page address |
Requested address |
Contenttype |
String |
"Application/X-WWW-form-urlencoded; charset = UTF-8" |
Content Encoding Method sent to the server |
Data |
Object, string |
|
Data sent to the server |
Datatype |
String |
Smart inference (XML, JSON, script, or HTML) |
The format of the data returned by the server ("XML"/"html"/"script"/"JSON"/"jsonp"/"text ") |
Success (data, textstatus, xhr) |
Function |
|
Callback function when the request is successful Data: The data returned by the server and processed in the specified format of datatype; Textstatus: string that describes the status; Xhr: XMLHTTPRequest object |
Error (xhr, textstatus, errorthrown) |
Function |
|
Callback function when the request fails Xhr: XMLHTTPRequest object; Textstatus: error message; Errorthrown: (optional) HTTP response text section (for example, "not found", "internal server error ") |
Complete (xhr, textstatus) |
Function |
|
The callback function when the request is complete (the callback function is called if the request is successful or fails) Xhr: XMLHTTPRequest object; Textstatus: Request status (for example, "success", "notmodified", "error", "timeout", "Abort", "parsererror ") |
Note the difference between contenttype and datatype. Because data is sent to the server, I often mistakenly identify datatype as a data type.Contenttype is the type of data that the client sends to the server. datatype is the data type returned by the request server.
Let's take a look at how jquery. Ajax works with several server interfaces:
1. jquery. Ajax and general processing Program (Handler. ashx)
When the server uses a general processing program, we usually manually submit the request. querystring or request. form to parse the client request data, so contenttype with the default "application/X-WWW-form-urlencoded; charset = UTF-8" is good, data I used to use key/value pairs to represent form data.
$. Ajax ({type: " Get " , URL: " Handler. ashx " , Data: {Name: ' Heku ' , Age: parseint (math. Random ()* 100 )}, // Data sent to the server Datatype: " JSON " , // The server must return JSON Error: function (xhr, textstatus, errorthrown) {alert ( " Xhr: " + Xhr + " -- Textstatus: " + Textstatus + " -- Errorthrown: " + Errorthrown);}, success: function (data, ts, xhr) {$ ( " # Div1 " ). Append (Data + " <Br/> " ) ;}, Complete: function () {$ ( " # Div1 " ). Append ( " Ajax access to the general handler is completed <br/> " );}});
In general, it should be noted that response. contenttype must be consistent with the type returned by datatype.
Public Void Processrequest (httpcontext context ){ String Name = context. request [ " Name " ]; String Age = context. request [ " Age " ]; String Type = Context. Request. requesttype; system. Threading. thread. Sleep ( 500 ); Context. response. contenttype = " Application/JSON " ; Javascriptserializer JSS = New Javascriptserializer (); String Resultstring = String . Format ( " [General handler (return JSON)] {0} -- {1} -- {2} -- {3} " , Datetime. Now. tostring (), name, age, type); context. response. Write (JSS. serialize (resultstring ));}
2. jquery. Ajax and WebService
When the server uses WebService to process data, if you want to return JSON-type data from the server, in addition to setting datatype to JSON, you also need to set contenttype to JSON and send JSON-type data to the server, I don't know why this is happening here.
$. Ajax ({type: " Post " , URL: " WebService. asmx/gettime " , Contenttype: " Application/JSON " , // Data transmission type Data: " {Name: 'heku ', age: " + Parseint (math. Random ()* 100 ) + " } " , // The JSON object must be enclosed in quotation marks. Datatype: " JSON " , // Required return and type Error: function (xhr) {alert ( " Error: " + Xhr. responsetext) ;}, success: function (data, ts, xhr) {$ ( " # Div1 " ). Append (data. d + " <Br/> " ) ;}, Complete: function () {$ ( " # Div1 " ). Append ( " Ajax access to WebService is complete <br/> " );}});
WebService can add the scriptmethod feature to indicate whether the request type it processes is "get" or "Post ".
[Webmethod]Public StringGettime (StringName,IntAge) {system. Threading. thread. Sleep (1000);Return String. Format ("[WebService method] Time: {0}, name: {1}, age: {2}", Datetime. Now. tostring (), name, age );}
3. jquery. Ajax and background Methods
This method is essentially the same as WebService, but it is a relatively lazy method. You do not need to add a handler. ashx or WebService. asmx. Directly on the Asp.net pageCodeFile, mark a method as webmethod.
Default. aspx (partial)
$. Ajax ({type: " Post " , URL: " Default. aspx/gettime " , Contenttype: " Application/JSON " , // Data transmission type Data: " {Name: 'heku ', age: " + Parseint (math. Random ()* 100 ) + " } " , // The JSON object must be enclosed in quotation marks. Datatype: " JSON " , // Required return and type Error: function (xhr) {alert ( " Error: " + Xhr. responsetext) ;}, success: function (data, ts, xhr) {$ ( " # Div1 " ). Append (data. d + " <Br/> " ) ;}, Complete: function () {$ ( " # Div1 " ). Append ( " Ajax background access method completed <br/> " );}});
Default. aspx. CS (Part)
[System. Web. Services. webmethod]Public Static StringGettime (StringName,IntAge) {system. Threading. thread. Sleep (1000);Return String. Format ("[Background method] Time: {0}, name: {1}, age: {2}", Datetime. Now. tostring (), name, age );}