Jquery journey-jquery's Ajax

Source: Internet
Author: User
Tags getscript

By jack_lee

$. Ajax (properties)

Use the HTTP request (XMLHttpRequest) to load a remote page.

This is jquery's low-level Ajax implementation. For more information about advanced abstraction, see $. Get and $. Post. Advanced content is often easy to understand and use, but more methods (such as error callback) are not provided ).

$. Ajax () returns the created XMLHTTPRequest object. In most cases, you do not need to directly manipulate this object, but it is also available if you need to manually stop the request.

Note: Make sure that the server returns the correct MIME type (for example, XML is "text/XML "). If the error MIME type is returned, it will cause serious problems that jquery cannot handle.

Supported data types include (see the datatype option ):

"XML": returns an XML document that can be processed by jquery objects.

"Html": returns HTML in plain text format, including the script tag after the value is evaluated.

"Script": evaluate the response as a javascript statement and return plain text.

"JSON": evaluate the response as JSON and return a JavaScript Object.

Option

$. Ajax () carries an object in the form of a parameter-"name/value pair", which is used to initialize and process requests. The following lists all available "name/value pairs ":

Async (Boolean)-by default, all requests are sent asynchronously (with the value true ). If you want to use the synchronization method, set this item to false.

Beforesend (function)-a pre-called function used to set information such as a custom header and receive a unique parameter-XMLHTTPRequest object.

Complete (function)-the function called when the request is complete. This function will get two parameters: the XMLHTTPRequest object and a string that describes the successful request type.

Contenttype (string)-set the content = type of the request to be sent. The default value is "application/X-WWW-form-urlencoded", which can meet the requirements in most cases.

Data (Object & #124; string)-data to be sent to the server. If not, it is automatically rotated into a query string. That is, the string appended to the URL of the GET request. To prevent automatic processing, see the processdata option. The object must be a key/value pair. If the value is an array, jquery uses multiple values for the same key consecutively. For example, {FOO: ["bar1 ", "bar2"]} is changed to '& Foo = var1 & Foo = bar2 '.

Datatype (string)-type of data to be returned from the server. No Default Value: if the server returns XML, it will pass responsexml to the callback function; otherwise, it will pass resposetext to the callback function.

Supported data types include (see the datatype option ):

"XML": returns an XML document that can be processed by jquery objects.

"Html": returns HTML in plain text format, including the script tag after the value is evaluated.

"Script": evaluate the response as a javascript statement and return plain text.

"JSON": evaluate the response as JSON and return a JavaScript Object.

Error (function)-the function called when the request fails. This function will get three parameters: XMLHTTPRequest object, a string describing the error type that occurred, and an optional exception object (if any ).

Global (Boolean)-whether to trigger a global Ajax event handler for the current request. The default value is true. Setting false can prevent triggering global event processing functions such as ajaxstart and ajaxstop.

Ifmodified (Boolean)-the request is successful only when the response is modified after the previous request. It is implemented by checking the value of last-modified in the header. The default value is false, that is, partial checks are ignored.

Processdata (Boolean)-by default, if the data option is passed into an object rather than a string, it will be automatically processed and converted into a query string, to adapt to the default Content-Type -- "application/X-WWW-form-urlencoded ". To send domdocuments, set this option to false.

Success (function)-the function called when the request is successful. This function will get a parameter: The data returned from the server (formatted according to "datatype ).

Timeout (number)-covers the local latency of global latency. For example, when all other latencies go through 1 second, start a separate request with a long latency. For more information about global latency, see $. ajaxtimeout ().

Type (string)-request type ("Post" or "get"). The default value is "get ".

URL (string)-the URL to which the request is sent.

Returned value: XMLHttpRequest
Parameters:
Propertites (MAP) form the key/value pair of this request

Example: load and execute a Javascript file
$. Ajax ({
Type: "Get ",
URL: "test. js ",
Datatype: "script"
})

 

Example: Save some data to the server and notify the user when the process is completed.
$. Ajax ({
Type: "Post ",
URL: "Some. php ",
Data: "name = John & location = Boston ",
Success: function (MSG ){
Alert ("data saved:" + MSG );
}
});

Example: load data synchronously. Blocks the browser while the requests is active when the request is available ). This can effectively prevent user interaction when synchronous processing is required.
VaR html = $. Ajax ({
URL: "Some. php ",
Async: false
}). Responsetext;

Example: Send an XML file as data to the server. By setting the processdata option to false, automatic changes to data to strings are avoided.
VaR xmldocument = & #91; create XML document & #93 ;;
$. Ajax ({
URL: "Page. php ",
Processdata: false,
Data: xmldocument,
Success: handleresponse
});

 

$. Ajaxsetup (settings)
Global settings for Ajax requests
For descriptions of all available options, see $. Ajax.

Returned value: Undefined
Parameters:
Settings (MAP) Key/value pairs used by all Ajax requests

Example:
Set the default URL "/XMLHTTP/" for Ajax requests, set all global processing functions to unavailable, and use post instead of get. The following Ajax request will send some data without setting anything.
$. Ajaxsetup ({
URL: "/XMLHTTP /",
Global: false,
Type: "Post"
});
$. Ajax ({data: mydata });

 

$. Ajaxtimeout (time)
Set a fixed timeout value for all Ajax requests. This will cause all Ajax requests to time out after a specific event.
If it is set to null or 0, timeout can be set to invalid (default)
You can manually use the abort () method of XMLHttpRequest to interrupt the request.

We do not agree to use this method instead of $. ajaxsetup.

Returned value: Undefined
Parameters:
Time (number) the number of milliseconds before an Ajax request times out.

Example:
Make all Ajax requests time out in 5 seconds
$. Ajaxtimeout (5000 );

$. Get (URL, Params, callback)
Use an http get request to load a remote page.
This is a simple GET Request Method sent to the server without using the complex $. Ajax method. It allows a specific individual callback method to be executed at the end of the request (only when the response has a successful response code ). If you need both an error callback and a successful callback, you can use $. Ajax.

Returned value: XMLHttpRequest
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method executed when data is loaded successfully

Example:
$. Get ("test. cgi ");

Example:
$. Get ("test. cgi", {name: "John", time: "2 "});

Example:
$. Get ("test. cgi", function (data ){
Alert ("data loaded:" + data );
});

Example:
$. Get ("test. cgi ",
{Name: "John", time: "2 "},
Function (data ){
Alert ("data loaded:" + data );
}
);

$. Getifmodified (URL, Params, callback)
Use an http get request to load a remote page. Only when it is obtained from the last time, when it is not modified (load a remote page using an http get request, only if it hasn' t been modified since it was last retrieved)

Returned value: XMLHttpRequest
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method executed when data is loaded successfully

Example:
$. Getifmodified ("test.html ");

Example:
$. Getifmodified ("test.html", {name: "John", time: "2 "});

Example:
$. Getifmodified ("test. cgi", function (data ){
Alert ("data loaded:" + data );
});

Example:
$. Getifmodified ("test. cgi ",
{Name: "John", time: "2 "},
Function (data ){
Alert ("data loaded:" + data );
}
);

$. Getjson (URL, Params, callback)
Use an http get request to load a JSON data

Returned value: XMLHttpRequest
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method executed when data is loaded successfully

Example:
$. Getjson ("test. js", function (JSON ){
Alert ("JSON data:" + JSON. Users & #91; 3 & #93;. Name );
});

Example:
$. Getjson ("test. js ",
{Name: "John", time: "2 "},
Function (JSON ){
Alert ("JSON data:" + JSON. Users & #91; 3 & #93;. Name );
}
);

 

Use the HTTP request (XMLHttpRequest) to load a remote page.

This is jquery's low-level Ajax implementation. For more information about advanced abstraction, see $. Get and $. Post. Advanced content is often easy to understand and use, but more methods (such as error callback) are not provided ).

$. Ajax () returns the created XMLHTTPRequest object. In most cases, you do not need to directly manipulate this object, but it is also available if you need to manually stop the request.

Note: Make sure that the server returns the correct MIME type (for example, XML is "text/XML "). If the error MIME type is returned, it will cause serious problems that jquery cannot handle.

Supported data types include (see the datatype option ):

"XML": returns an XML document that can be processed by jquery objects.

"Html": returns HTML in plain text format, including the script tag after the value is evaluated.

"Script": evaluate the response as a javascript statement and return plain text.

"JSON": evaluate the response as JSON and return a JavaScript Object.

Option

$. Ajax () carries an object in the form of a parameter-"name/value pair", which is used to initialize and process requests. The following lists all available "name/value pairs ":

Async (Boolean)-by default, all requests are sent asynchronously (with the value true ). If you want to use the synchronization method, set this item to false.

Beforesend (function)-a pre-called function used to set information such as a custom header and receive a unique parameter-XMLHTTPRequest object.

Complete (function)-the function called when the request is complete. This function will get two parameters: the XMLHTTPRequest object and a string that describes the successful request type.

Contenttype (string)-set the content = type of the request to be sent. The default value is "application/X-WWW-form-urlencoded", which can meet the requirements in most cases.

Data (Object & #124; string)-data to be sent to the server. If not, it is automatically rotated into a query string. That is, the string appended to the URL of the GET request. To prevent automatic processing, see the processdata option. The object must be a key/value pair. If the value is an array, jquery uses multiple values for the same key consecutively. For example, {FOO: ["bar1 ", "bar2"]} is changed to '& Foo = var1 & Foo = bar2 '.

Datatype (string)-type of data to be returned from the server. No Default Value: if the server returns XML, it will pass responsexml to the callback function; otherwise, it will pass resposetext to the callback function.

Supported data types include (see the datatype option ):

"XML": returns an XML document that can be processed by jquery objects.

"Html": returns HTML in plain text format, including the script tag after the value is evaluated.

"Script": evaluate the response as a javascript statement and return plain text.

"JSON": evaluate the response as JSON and return a JavaScript Object.

Error (function)-the function called when the request fails. This function will get three parameters: XMLHTTPRequest object, a string describing the error type that occurred, and an optional exception object (if any ).

Global (Boolean)-whether to trigger a global Ajax event handler for the current request. The default value is true. Setting false can prevent triggering global event processing functions such as ajaxstart and ajaxstop.

Ifmodified (Boolean)-the request is successful only when the response is modified after the previous request. It is implemented by checking the value of last-modified in the header. The default value is false, that is, partial checks are ignored.

Processdata (Boolean)-by default, if the data option is passed into an object rather than a string, it will be automatically processed and converted into a query string, to adapt to the default Content-Type -- "application/X-WWW-form-urlencoded ". To send domdocuments, set this option to false.

Success (function)-the function called when the request is successful. This function will get a parameter: The data returned from the server (formatted according to "datatype ).

Timeout (number)-covers the local latency of global latency. For example, when all other latencies go through 1 second, start a separate request with a long latency. For more information about global latency, see $. ajaxtimeout ().

Type (string)-request type ("Post" or "get"). The default value is "get ".

URL (string)-the URL to which the request is sent.

Returned value: XMLHttpRequest
Parameters:
Propertites (MAP) form the key/value pair of this request

Example: load and execute a Javascript file
$. Ajax ({
Type: "Get ",
URL: "test. js ",
Datatype: "script"
})

 

Example: Save some data to the server and notify the user when the process is completed.
$. Ajax ({
Type: "Post ",
URL: "Some. php ",
Data: "name = John & location = Boston ",
Success: function (MSG ){
Alert ("data saved:" + MSG );
}
});

Example: load data synchronously. Blocks the browser while the requests is active when the request is available ). This can effectively prevent user interaction when synchronous processing is required.
VaR html = $. Ajax ({
URL: "Some. php ",
Async: false
}). Responsetext;

Example: Send an XML file as data to the server. By setting the processdata option to false, automatic changes to data to strings are avoided.
VaR xmldocument = & #91; create XML document & #93 ;;
$. Ajax ({
URL: "Page. php ",
Processdata: false,
Data: xmldocument,
Success: handleresponse
});

 

$. Ajaxsetup (settings)
Global settings for Ajax requests
For descriptions of all available options, see $. Ajax.

Returned value: Undefined
Parameters:
Settings (MAP) Key/value pairs used by all Ajax requests

Example:
Set the default URL "/XMLHTTP/" for Ajax requests, set all global processing functions to unavailable, and use post instead of get. The following Ajax request will send some data without setting anything.
$. Ajaxsetup ({
URL: "/XMLHTTP /",
Global: false,
Type: "Post"
});
$. Ajax ({data: mydata });

 

$. Ajaxtimeout (time)
Set a fixed timeout value for all Ajax requests. This will cause all Ajax requests to time out after a specific event.
If it is set to null or 0, timeout can be set to invalid (default)
You can manually use the abort () method of XMLHttpRequest to interrupt the request.

We do not agree to use this method instead of $. ajaxsetup.

Returned value: Undefined
Parameters:
Time (number) the number of milliseconds before an Ajax request times out.

Example:
Make all Ajax requests time out in 5 seconds
$. Ajaxtimeout (5000 );

$. Get (URL, Params, callback)
Use an http get request to load a remote page.
This is a simple GET Request Method sent to the server without using the complex $. Ajax method. It allows a specific individual callback method to be executed at the end of the request (only when the response has a successful response code ). If you need both an error callback and a successful callback, you can use $. Ajax.

Returned value: XMLHttpRequest
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method executed when data is loaded successfully

Example:
$. Get ("test. cgi ");

Example:
$. Get ("test. cgi", {name: "John", time: "2 "});

Example:
$. Get ("test. cgi", function (data ){
Alert ("data loaded:" + data );
});

Example:
$. Get ("test. cgi ",
{Name: "John", time: "2 "},
Function (data ){
Alert ("data loaded:" + data );
}
);

$. Getifmodified (URL, Params, callback)
Use an http get request to load a remote page. Only when it is obtained from the last time, when it is not modified (load a remote page using an http get request, only if it hasn' t been modified since it was last retrieved)

Returned value: XMLHttpRequest
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method executed when data is loaded successfully

Example:
$. Getifmodified ("test.html ");

Example:
$. Getifmodified ("test.html", {name: "John", time: "2 "});

Example:
$. Getifmodified ("test. cgi", function (data ){
Alert ("data loaded:" + data );
});

Example:
$. Getifmodified ("test. cgi ",
{Name: "John", time: "2 "},
Function (data ){
Alert ("data loaded:" + data );
}
);

$. Getscript (URL, callback)
Use an http get request to load and execute a remote Javascript file

Returned value: XMLHttpRequest
Parameters:
URL (string) the URL of the page to load
Callback (function) (optional) method executed when data is loaded successfully

Example:
$. Getscript ("test. js ");

Example:
$. Getscript ("test. js", function (){
Alert ("script loaded and executed .");
});

$. Post (URL, Params, callback)
Use an http post request to load a remote page.
This is a simple POST Request Method sent to the server without using the complex $. Ajax method. It allows a specific individual callback method to be executed at the end of the request (only when the response has a successful response code ). If you need both an error callback and a successful callback, you can use $. Ajax.

Returned value: XMLHttpRequest
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method executed when data is loaded successfully

Example:
$. Post ("test. cgi ");

Example:
$. Post ("test. cgi", {name: "John", time: "2 "});

Example:
$. Post ("test. cgi ",
{Name: "John", time: "2 "},
Function (data ){
Alert ("data loaded:" + data );
}
);

Ajaxcomplete (callback)
Add an executed method when the Ajax request is complete.
Both XMLHttpRequest and its settings are passed to the callback function as a parameter.

Returned value: jquery
Parameters:
Callback (function) method to be executed

Example: A message is displayed when the Ajax request is complete.
$ ("# MSG"). ajaxcomplete (function (request, settings ){
$ (This). append ("<li> request complete. </LI> ");
});

Ajaxerror (callback)
Add an executed method when the Ajax request fails.
Both XMLHttpRequest and its settings are passed to the callback function as a parameter. The third parameter, an exception object, will be passed when an exception occurs during the execution of this request.

Returned value: jquery
Parameters:
Callback (function) method to be executed

Example: A message is displayed when a failure occurs.
$ ("# MSG"). ajaxerror (function (request, settings ){
$ (This). append ("<li> error requesting page" + settings. url + "</LI> ");
});

Ajaxsend (callback)
Add a method to be executed before the Ajax request is submitted
Both XMLHttpRequest and its settings are passed to the callback function as a parameter.

Returned value: jquery
Parameters:
Callback (function) method to be executed

Example: A message is displayed before an Ajax request is submitted.
$ ("# MSG"). ajaxsend (function (request, settings ){
$ (This). append ("<li> starting request at" + settings. url + "</LI> ");
});

Ajaxstart (callback)
When an Ajax request starts and is not activated, add a method to be executed.

Returned value: jquery
Parameters:
Callback (function) method to be executed

Example: A loading message is displayed when an Ajax request starts (and is not activated ).
$ ("# Loading"). ajaxstart (function (){
$ (This). Show ();
});

Ajaxstop (callback)
Add an executed method when an Ajax request ends.

Returned value: jquery
Parameters:
Callback (function) method to be executed

Example: hide a piece of loading information when an Ajax request is stopped
$ ("# Loading"). ajaxstop (function (){
$ (This). Hide ();
});

Ajaxsuccess (callback)
When an Ajax request ends successfully, add a method to be executed.
Both XMLHttpRequest and its settings are passed to the callback function as a parameter.

Returned value: jquery
Parameters:
Callback (function) method to be executed

Example: A message is displayed when the Ajax request ends successfully.
$ ("# MSG"). ajaxsuccess (function (request, settings ){
$ (This). append ("<li> Successful request! </LI> ");
});

Load (URL, Params, callback)
Load HTML from a remote file and inject it into the DOM
Tip: Avoid using this method to load the script and replace it with $. getscript.

Returned value: jquery
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method to be executed after data is loaded (parameters: responsetext, status, and response.

Example:
$ ("# Feeds"). Load ("feeds.html ");

Before:
<Div id = "feeds"> </div>

Result:
<Div id = "feeds"> <B> 45 </B> feeds found. </div>

Example: The same as the example above, but when the data is loaded, an additional parameter and a callback executed
$ ("# Feeds"). Load ("feeds.html ",
{Limit: 25 },
Function () {alert ("the last 25 entries in the feed have been loaded ");}
);

Loadifmodified (URL, Params, callback)
Only when it is modified by the server, it loads HTML from a remote file and injects it into the Dom.

Returned value: jquery
Parameters:
URL (string) the URL of the page to load
Params (MAP) (optional) Key/value pair to be sent to the server
Callback (function) (optional) method to be executed after data is loaded (parameters: responsetext, status, and response.

Example:
$ ("# Feeds"). loadifmodified ("feeds.html ");

Before:
<Div id = "feeds"> </div>

Result:
<Div id = "feeds"> <B> 45 </B> feeds found. </div>

Serialize ()
Concatenates a series of input elements into a data string. This will concatenate all the given elements.
A serialization designed to emulate the actual form submission of a browser is provided by the form plugin. the plugin's formserialize method correctly handles multiple-selects and identically-named checkboxes as arrays, whereas the serialize method recognizes only a single value for these elements.

Return Value: String
Example:
Serialize a selection of input elements to a string
$ ("Input & #91; @ type = text & #93;"). serialize ();

Before:
<Input type = 'text' name = 'name' value = 'john'/>
<Input type = 'text' name = 'location' value = 'boston '/>

Result:
Name = John & location = Boston

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.