$. Get (), $. post (), $. ajax (), $. getJSON () in Jquery, and jquery. post
This article describes $. get (), $. post (), $. ajax (), $. the usage of getJSON () is summarized in detail. For more information, see getJSON.
Details about Jquery Ajax functions:$. Get (), $. post (), $. ajax (), $. getJSON ()
1, $. get (url, [data], [callback])
Note: The url is the request address, the data is the list of request data, and the callback is the callback function after the request is successful. This function accepts two parameters. The first one is the data returned by the server, the second parameter is the server status, which is an optional parameter.
The format of the data returned by the server is actually the string format, not the json data format we want. Here we reference it for comparison.
The Code is as follows: $. get ("data. php", $ ("# firstName. val ()"), function (data ){
$ ("# GetResponse" ).html (data);} // The returned data is of the string type.
);
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 data type of the request, 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 $. get () returns the same format as a string.
The Code is as follows: $. post ("data. php", $ ("# firstName. val ()"), function (data ){
$ ("# PostResponse" pai.html (data. name );
}, "Json" // sets the type of data to be retrieved, so the obtained data format is json
);
3, $. ajax (opiton)
: $. Ajax () is a powerful function that provides many precise control over ajax. For details, see relevant materials.
The Code is as follows: $. ajax ({
Url: "ajax/ajax_selectPicType.aspx ",
Data: {Full: "fu "},
Type: "POST ",
DataType: 'json ',
Success: CallBack,
Error: function (er ){
BackErr (er );}
});
4, $. getJSON (url, [data], [callback])
$. GetJSON ("data. php", $ ("# firstName. val ()"), function (jsonData ){
$ ("# GetJSONResponse" ).html (jsonData. id);} // The directly obtained data type is json. Therefore, jsonData. id is required for calling.
);
When Ajax meets jQuery has more and more AJAX-based applications. For front-end developers, it is not a pleasant thing to deal directly with the underlying HTTPRequest. Since jQuery encapsulates JavaScript, you must have considered AJAX applications. Indeed, writing AJAX with jQuery is N times more convenient than writing with JS directly. (I don't know if I will lose my knowledge of JS after I use jQuery ......) Let's assume that you are familiar with jQuery syntax to summarize some ajax applications.
Load Static pages
Load (url, [data], [callback]);
Url (String) the URL address of the HTML page data (Map) (optional) the key/value data callback (Callback) sent to the server (optional parameter) 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.
The Code is as follows: ('{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:
The Code is as follows: ('{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.
The Code is as follows: $. get ('login. php ', {id: 'Robin', password: '123', gate: 'index'}, function (data, status) {// data is the returned object, status indicates the Request status alert (data); // assume that the server script returns a text "Hello, Robin! ", Then the browser will pop up the dialog box to display the text alert (status); // The result is success, error, and so on, but here is the function that can be run when it 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 and Its Usage
The Code is as follows: $. post ('regsiter. php ', {id: 'Robin', password: '123456', 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.
The Code is as follows: $. getScript ('ajaxevent. js', function () {alert ("Scripts Loaded! "); // Load ajaxEvent. js, and a dialog box prompt is displayed after loading successfully. });
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.
The Code is as follows: $. getJSON ('feed. php ', {request: images, id: 001, size: large}, function (json) {alert (json. images [0]. link); // 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 :}//] };});
Although get () and post () functions are simple and easy to use, the underlying ajax () functions still cannot be implemented for more complex design requirements, for example, you can make different actions in 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 |
Set the request timeout (in milliseconds ). This setting overwrites the global setting. |
Async |
Boolean |
(Default: true) by default, all requests are asynchronous requests. 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. |
BeforeSend |
Function |
Before sending a request, you 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. |
Complete |
Function |
Callback Function after the 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} 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 |
The 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 ′. |
DataType |
String |
Expected data type returned by the server. If this parameter is not specified, jQuery will automatically return responseXML or responseText Based on the MIME information of the HTTP package and pass it 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. |
Error |
Function |
(Default: automatically determines (xml or html) This method is called when a request fails. This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object. Function (XMLHttpRequest, textStatus, errorThrown) {// Generally, only one of textStatus and errorThown has the value this; // the options for this ajax request} function (XMLHttpRequest, textStatus, errorThrown) {// Generally, only one of textStatus and errorThown has the value this; // the options for this ajax request} |
Global |
Boolean |
(Default: true) Whether to trigger 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) obtain 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. |
Success |
Function |
Callback Function after successful 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} 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:
The Code is as follows: $. ajax ({url: 'doc. xml', type: 'get', ype: '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 methods such as find (), next (), or XPath to find nodes in it, there is no difference from using jQuery to operate HTML Objects }});
To learn more about AJAX events, some of the methods discussed earlier have their own event processing mechanisms. From the perspective of the page as a whole, they can only be called partial functions. 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.
An error 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 events) When Ajax is not in progress, triggering local events is described in previous functions. Let's take a 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:
The Code is as follows: $ ("# 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:
The Code is as follows: $ ("# msg "). beforeSend (function (e, xhr, o) {response (this).html ("requesting" + o. url );}). ajaxSuccess (function (e, xhr, o) {detail (this).html (o. url + "request succeeded ");}). ajaxError (function (e, xhr, o) {timeout (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.
The Code is as follows: $. ajax ({url: "request. php", 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:
The Code is as follows: $. ajaxSetup ({url: "request. php", global: false, type: "POST "});
Some methods you have to know to write AJAX are definitely inseparable from getting the corresponding value from the page. Here are some simple examples:
The val () function can return the values of form elements, for example, input values 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.
The Code is as follows: $ ("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 (); // return 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 () is similar to serialize (), but it returns a JSON object.
PS: This site also provides several powerful json parsing, conversion and formatting tools for your choice. I believe this will be helpful for your next json format data processing:
Online JSON code verification, validation, beautification, and formatting tools:Http://tools.jb51.net/code/json
Online XML/JSON conversion:Http://tools.jb51.net/code/xmljson
Json code online formatting/beautification/compression/editing/conversion tools:Http://tools.jb51.net/code/jsoncodeformat
C language style/HTML/CSS/json code formatting and beautification tools:Http://tools.jb51.net/code/ccode_html_css_json
Source: http://www.jb51.net/article/43194.htm