Summary: six Ajax data interaction applications in jquery

Source: Internet
Author: User
Tags getscript http request json

Several ajax requests in jquery, including the underlying method $. ajax (), Layer 2 load (), $. post (), $. ajax (), Layer 3 $. getJSON (), $. getScript ().

The code is as follows: Copy code
<Script type = "text/javascript">
// Several ajax requests in jquery
Function ajaxRequest (){

/*
$. Ajax (); underlying method
Load (), $. post (), $. ajax (); Layer 2
$. GetJSON (); $. getScript (); // layer 3
/*
/****************************** Load method ****** **************************/
// Url address/data transmission data json format key-value pair/callback function load is usually used
// Retrieving static data files on the web does not reflect the full value of ajax
Load (url, [data (key/value)], [callback]);
// 1. load can add remote html code to the dom
$ ("# Text"). load ("test.html ");
// 2. load filtering and loading html documents
$ ("# Text"). load ("test.html. para ");
// 3. Transfer method get
$ ("# Text"). load ("test. php", function (){
//...
});
// Transfer method post
$ ("# Text"). load ("test. php", {name: "rain", age: "22"}, function (){
//...
});
// 4. Callback function
$ ("# Text"). load ("test.html", function (responseText, textStatus, XMLHttpRequest ){
// ResponsetText content returned by the request
// TextStatus: Four request statuses: success, error, notmodified, and timeout
// XMLHttpRequest object
});
      
/*************************************** ********************************* ***************/
// $. Get (); use GET asynchronous request
/* Url address/data transmission data json format key-value pair/calback callback function/type return type ()
The callback function has two functions (data, textStatus). data can return xml, json files, and html fragments.
TextStatus: success, error, notmodified, and timeout
TextStatus is called only when success is returned. This is different from load.
*/
$. Get (url, [. data], [. calback], [. type]);
$. Get ("test. action", {name: "zhangsan", age: "10"}, function (data, textStatus ){
           
/*... The last parameter indicates that the returned data is in json format.
Json format is very strict {"name": "James", "age", "20"} must be in this format rather
{Name: "zhangsan", age: "10"} any one of {} does not match to obtain a missing comma, which causes the script on the page to stop running.
It may even cause other more serious negative effects. Of course, javascript will not be available in the future.
Xml is as easy to parse as json, and the parsed xml will become the mainstream data exchange format, but before it
Still have strong vitality
*/
}, "Json ");
/*************************************** ********************************* ***************/
/*
       
The difference between $. post () and get requests
1. GET will pass the parameters following the URL, while the POST request is the entity content of the HTTP message.
Send to the WEB server. Of course, in Ajax requests, this difference is visible to users.
       
2. The GET method imposes a limit on the size of the transmitted data (usually not greater than 2 kB), but the POST method is used for transmission.
The data volume is much larger than the GET method (theoretically unlimited)

3. The data requested by the GET method will be cached by the browser, so others can record the data from the browser.
To read the data, such as the account and password. In some cases, the GET method brings serious security.
And the POST method can avoid these problems.

4. Data transmitted by the GET method and POST method is also obtained on the server. In PHP, the GET method
The data can be obtained using $ _ GET [], while the POST method can be obtained using $ _ POST []. Both methods can be used.
$ _ REQUEST.
       
$. Post (url, [. data], [. calback], [. type]);
*/

$. Post ("test. action", {name: "zhangsan", age: "10"}, function (data, textStatus ){
// ...... In addition, when the load method has parameters passed, the post request will be used to send the request.
}, "Json ");

/*************************************** ********************************* ***************/
/*
To use the load $. get () $. post () method to complete some common Ajax programs, you need to write some complex Ajax programs,
$. Ajax (); can be used not only to implement the same functions as the load, get, and post methods, but also
You can also set beforeSend (callback function before submission), error (request failed processing), and success (request successful
After processing) and complete (after the request is completed) callback functions, through these callback functions, you can give more
. In addition, there are some parameters that can be used to set the Ajax request timeout time or the last modification status of the page.
.
       
Parameters in ajax
Url: (the default is the current webpage address) the address that sends the request
Type: The default post and get request methods are get. Pay attention to the http request methods, such as PUT and DELETE,
However, only some browsers support
Timeout: sets the request timeout (MS). This setting overwrites the global variables of the $. ajaxSetup () method.
Data: The data sent to the server can be followed by the URL or the key/value pair in json format.
DataType: the returned data types include xml, html, script, json, jsonp, and text.
BeforeSend: a function that sends a request to modify the XMLHttpRequest object, for example, adding a custom HTTP header,
In beforeSend, if false is returned, the unique parameters of the ajax request, XmLHttpRequest object,
Function (XMLHttpRequest ){
This; // call the options parameter passed by the Beibei Ajax request
        }
Complete: The callback function called in red when the request is completed (all calls fail to succeed)
Success: callback function called successfully. There are two parameters. 1. The response is returned by the server and the Ype parameter is added.
The processed data. 2. String describing the status
Function (data, textStatus ){
// Data may be xmlDac, jsonObj, html, text, etc.
This; // call the options parameter passed in this ajax request
        }
       
Error: The function called when the request fails. The function has three parameters: XMLHttpRequest object, error message, and captured error.
(Optional ). Ajax time functions are as follows:
Function (XMLHttpRequest, textStatus, errorThrown ){
// Generally, only one of the textStatus River errorThown contains information,
This; calling this Ajax request is the passed options parameter
       
        }
Global: The default value is true, indicating whether to trigger a global Ajax event. Setting false does not trigger global Ajax events, such as AjaxStart or
AjaxStop controls various Ajax events
*/
$. Ajax ({
Type: "POST", // request method
Url: "test.html", // url access address
Data: {name: "War 3", age: "11"} // pass parameters
DataType: "json", // return value type
Success: function (data) {// successful data processing
// Data... data processing
           
},
Error: function (msg) {// failed to process
Alert (msg );
            }
           
});
/*************************************** ********************************* ***************/
/*
Only use post and get to pass parameters. If there is too much data in a form, it will be a little troublesome.
Serialize (); serialize the dom object into a string.
$ ("# Form1"). serizlize ();
$. Post ("this.html", $ ("# form1"). serizlize (), function (data ){
// Process...
})
   
The serizlizeArray method returns not a string, but a serialized dom element and a formatted data,
$. Param () method: it is the core of the serizlize () method, used to serialize an array or object according to kay/value.
Var obj = {a: 1, B: 2, c: 3 };
Var k = $. param (obj );
Alert (k); // output a = 1 & B = 2 & c3
*/
/*************************************** ********************************* ***************/

/*
Sometimes, when loading a page for the first time, you do not need to add all js files to dynamically create and load js files.
You can use $. getScript ();
*/
$ ("# Send"). click (function (){
$. GetScript ("js. js ");
});
/*************************************** * ***** GetJSON method ********************************* ***************/

/*
$. GetJSON () is used to load a JSON file in the same way as getScript ().
*/
$ ("# Send"). click (function (){
$. GetJSON ("js. json ");
});
$ ("# Send"). click (function (){
$. GetJSON ("js. json", function (data ){
// Data processing
});
});

    }
}
</Script>

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.