Details about jquery Ajax functions: $. Get (), $. Post (), $. Ajax (), $. getjson ()

Source: Internet
Author: User
Tags getscript

1, $. Get (URL, [data], [callback])

Note: The URL is the request address, the data is the list of request data (optional, you can also write the parameters to be passed in the URL), and the callback is the callback function after the request is successful, this function accepts two parameters. The first parameter is the data returned by the server, and the second parameter is the status of the server. It is an optional parameter. The format of the data returned by the server is actually a string, not the JSON data format we want. The reference here is only for comparison.

1 $ .get ("data.php", $ ("# firstName.val ()"), function (data) {
2 
3 $ ("# getResponse"). Html (data);} // The returned data is a string type
4
5);

 

Ii. $. Post (URL, [data], [callback], [type])

Note: This function and $. the get () parameter is similar. A type parameter is added, and the type is the returned data type, which can be HTML, XML, JSON, and Other types. If we set this parameter to JSON, the returned format is in JSON format. If no value is set, it is equal to $. the format returned by get () is the same as that returned by get.

1 $ .post ("emp.do?p=getAllEmp", {id: deptId, x: Math.random ()}, function (data) {
2 var arry = eval ("(" + data + ")"); // quote out, quote the json string and program the json type array, or add a parameter "json" after the $ .post function, specifying Data is of json type
3 for (var i = 0; i <arry.length; i ++) {
4 var op = new Option (arry [i] .empName, arry [i] .empId);
5 document.getElementById ("emp"). Options.add (op);
6}
7});

You can also write it as follows. The returned result is an array of the JSON type. You can directly traverse the array.

 
1 $.post("emp.do?p=getAllEmp",{id:deptId,x:Math.random()},function(arry){
2             for(var i=0;i<arry.length;i++){
3                 var op = new Option(arry[i].empName,arry[i].empId);
4                 document.getElementById("emp").options.add(op);
5             }
6         },"json");

3, $. Ajax (opiton)

: $. Ajax () is a powerful function that provides many precise control over Ajax. For details, see relevant materials.

 
1 $.ajax({
2   url: "ajax/ajax_selectPicType.jsp",
3   data:{Full:"fu"},
4   type: "POST",
5   dataType:'json',
6   success:CallBack,
7   error:function(er){
8   BackErr(er);}
9 });

4, $. getjson (URL, [data], [callback])

Note: The $. getjson (URL, [data], [callback]) function does not have the type parameter. The return value is of the JSON type and does not need to be converted.

 
1 $.getJSON("dep.do?p=getAllDep",{x:Math.random()},function(arry){
2             for(var i=0;i<arry.length;i++){
3                 var op = new Option(arry[i].deptName,arry[i].deptId);
4                 document.getElementById("dep").options.add(op);
5             }
6         });

 

Other functions of jquery:

Load Static pages

Load (URL, [data], [callback]);
URL (string) URL of the requested HTML page
Data (MAP) (optional parameter) Key/value data sent to the server
Callback (callback) (optional) callback function when the request is completed (success is not required)

The load () method can easily Load Static page content to a specified jquery object.
('{Ajax-div'{.load('data.html ');

In this example, the content of data.html is loaded into the DOM object with the ID Ajax-Div. You can even create an ID to load part of the content, such:

('{Ajax-div'{.load('data.html # My-section ');
Implement get and post Methods

Get (URL, [data], [callback])
URL (string) the URL of the request sent.
Data (MAP) (optional parameter) the data to be sent to the server, expressed in key/value pairs, will be appended to the request URL as querystring
Callback (callback) (optional parameter) callback function when the load is successful (this method is called only when the response returns success)

Obviously, this is a function dedicated to implementing the get method, and it is quite simple to use.
$. Get ('login. js ',{
ID: 'Robin ',
Password: '000000 ',
Gate: 'index'
}, Function (data, status ){
// Data is the returned object, and status is the Request status
Alert (data );
// Assume that the server script returns a piece of text. "Hello, Robin! ",
Then the browser will pop up a dialog box showing the text of this section.
Alert (Status );
// The result is success, error, and so on, but this is a function that can be run only when the operation is successful.
});

 

Post (URL, [data], [callback], [type])

URL (string) the URL of the request sent.
Data (MAP) (optional parameter) data to be sent to the server, expressed in key/value pairs
Callback (callback) (optional parameter) callback function when the load is successful (this method is called only when the response returns success)
Type (string) (Optional) Type of request data, XML, text, JSON, etc.

It is also a simple function provided by jquery.
 
$. Post ('regsiter. jsp ',{
ID: 'Robin ',
Password: '000000 ',
Type: 'user'
}, Function (data, status ){
Alert (data );
}, "JSON ");

 

Event-Driven Script Loading Function: getscript ()

Getscript (URL, [callback])
URL (string) Address of the JS file to be loaded
Callback (function) (optional) callback function after successful Loading

The getscript () function can remotely load and execute JavaScript scripts. This function can load JS files across domains (MAGIC ......?!). This function is of great significance. It can greatly reduce the amount of code that the page loads for the first time, because you can load the corresponding JS file based on user interaction, instead of loading all the pages during page initialization.
 
$. Getscript ('ajaxevent. js', function (){
Alert ("scripts loaded! ");
// Load ajaxevent. JS, and a dialog box prompt is displayed after the load is successful.
});

 

Build a bridge for data communication: getjson ()

Getjson (URL, [data], [callback])
URL (string) Sending request address
Data (MAP) (optional) Key/value parameter to be sent
Callback (function) (optional) callback function when the load is successful.

JSON is an ideal data transmission format. It can be well integrated with JavaScript or other remote languages and can be directly used by Js. JSON is more reasonable and secure in structure than the traditional "naked" data directly sent through get and post. For jquery's getjson () function, it is only a simplified version of AJAX () function with JSON parameters. This function can also be used across domains. It has some advantages over get () and post. In addition, this function can write the request URL as "myurl? Callback = x ", which allows the program to execute the callback function x.

$. Getjson ('feed. js ',{
Request: images,
ID: 001,
Size: Large
}, Function (JSON ){
Alert (JSON. Images [0]. Link );
// Here, JSON is the JSON object returned remotely. Assume the format is as follows:
// {'Images ':[
// {Link: images/001.jpg, X: 100, Y: 100 },
// {Link: images/002.jpg, X: 200, Y 200 :}
//]};
}
);

 

Underlying Ajax () Functions
Although get () and post () functions are simple and easy to use, they still cannot be implemented for more complex design requirements, such as making different actions at different time periods of Ajax sending. Jquery provides a more specific function: Ajax ().

Ajax (options)
Ajax () provides a large ticket parameter, so it can implement quite complex functions.

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"). The default value is "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 ′.
The data type that the datatype string expects to return from the server. If this parameter is not specified, jquery automatically uses the mime information of the http package.
Responsexml or responsetext is returned and passed as a callback function parameter. Available values:

"XML": the XML document is returned and 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,

For example, "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,

For example, 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
}

 

 

You can specify XML, script, HTML, and JSON as data types, and set processing functions for beforesend, error, sucess, complete, and other States, many other parameters can also fully define the user's Ajax experience. In the following example, we use Ajax () to call an XML document:

$. Ajax ({
URL: 'doc. xml ',
Type: 'get ',
Datatype: 'xml ',
Timeout: 1000,
Error: function (){
Alert ('error loading XML document ');
},
Success: function (XML ){
Alert (XML );
// Here, XML is the jquery object of XML. You can use the find (), next (), or XPath methods to find nodes in it,
It is no different from using jquery to operate HTML objects.
}
});

Learn more about Ajax events
Some of the methods discussed earlier have their own event processing mechanisms. In general, they can only be called partial functions on the page. Jquery provides the definition of Ajax global functions to meet special requirements. Below are all functions provided by jquery (arranged in the order of triggering ):

Ajaxstart
(Global Event) starts a new Ajax request, and no other Ajax requests are in progress at this time.
Beforesend
(Partial event) triggered when an Ajax request starts. If needed, you can set the XMLHTTPRequest object here.
Ajaxsend
(Global Event) global events triggered before the request starts
Success
(Partial event) triggered when the request is successful. That is, the server does not return errors, and the returned data is not.
Ajaxsuccess
The global event request is successful.
Error
(Partial event) is triggered only when an error occurs. You cannot execute both the success and error callback functions at the same time.
Ajaxerror
Triggered when a global error occurs.
Complete
(Partial event) Whether your request succeeds or fails, even if it is a synchronous request, you can trigger this event when the request is complete.
Ajaxcomplete
Triggered when a global event request is complete.
Ajaxstop
(Global Event) triggered when no Ajax is in progress
Local events are described in previous functions. We mainly look at global events. When a global event is monitored for an object, the global Ajax action will affect it. For example, when a page is performing Ajax operations, the DIV with the ID of "loading" is displayed:

 
$ ("# Loading"). ajaxstart (function (){
$ (This). Show ();
});

 

Global events can also help you write global errors and success responses without setting them for each Ajax request. It is worth noting that global event parameters are very useful. In addition to ajaxstart and ajaxoptions, other events have three parameters: event, XMLHttpRequest, and ajaxoptions. The first parameter is the event itself, the second is the xhr object, and the third is the Ajax parameter object you passed. Display the global Ajax situation in an object:

$ ("# MSG"). beforesend (function (E, xhr, O ){
Authorization (thisdomain.html ("requesting" + O. url );
}). Ajaxsuccess (function (E, xhr, O ){
Optional (this).html (O. url + "request successful ");
}). Ajaxerror (function (E, xhr, O ){
Optional (this).html (O. url + "request failed ");
});

 

Obviously, the third parameter can also help you to pass custom parameters that you add to the Ajax event. In a single Ajax request, you can set the global value to false to separate the request from the global events of Ajax.

 
$. Ajax ({
URL: "request. jsp ",
Global: false,
// Disable global Ajax events.
});

 

If you want to set parameters for global Ajax, you will use the ajaxsetup () function. For example, to pass all Ajax requests to request. php, disable the global method, and force the POST method to pass:

$. Ajaxsetup ({
URL: "request. jsp ",
Global: false,
Type: "Post"
});

 

Some methods you have to know
To write Ajax, you must obtain the corresponding values from the page. Here are some simple examples:

Val ()
The Val () function can return the value of form creation, for example, the value of input of any type. In combination with the selector operation, you can easily obtain the values of the sequence group, input boxes, buttons, and other elements.

$ ("Input [name = 'info']: Text"). Val ();
// Return the value of the text box whose name is info.
$ ("Input [name = 'pass']: Password"). Val ();
// Return the value of the password box named pass.
$ ("Input [name = 'save']: Radio"). Val ();
// Returns the value of a single option named "save ".
// And so on

 

Serialize ()

The serialize function can help you convert all values of form objects into string sequences. If you want to write a GET request, this is very convenient.
Serializearray ()
Similar to serialize (), but it returns a JSON object.

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.