Read more about jquery's Ajax functions:
$.get (), $.post (), $.ajax (), $.getjson ()
One, $.get (Url,[data],[callback])
Description: The URL is the request address, data is the list of requests, callback is a successful callback function, the function accepts two parameters, the first data returned for the server, the second parameter is the state of the server, optional parameters.
In this case, the server returns the data format is actually a string situation, not the JSON data format we want, this reference is just for comparison
Copy Code code as follows:
$.get ("data.php", $ ("#firstName. Val ()"), function (data) {
$ ("#getResponse"). HTML (data); The data returned by}//is a string type
);
Two, $.post (Url,[data],[callback],[type])
Description: This function is similar to the $.get () parameter, more than a type parameter, type is the requested data type, can be html,xml,json and other types, if we set this parameter to: JSON, then the return format is JSON format, if not set, and $. Get () is returned in the same format as a string of
Copy Code code as follows:
$.post ("data.php", $ ("#firstName. Val ()"), function (data) {
$ ("#postResponse"). HTML (data.name);
"JSON"//Set the type of get data, so the data format is JSON type
);
three, $.ajax (Opiton)
Description: $.ajax () This function is powerful, you can do a lot of precise control of Ajax, you need to specify the relevant information to refer to
Copy Code code as follows:
$.ajax ({
URL: "Ajax/ajax_selectpictype.aspx",
Data:{full: "Fu"},
Type: "POST",
DataType: ' JSON ',
Success:callback,
Error:function (er) {
Backerr (ER);
});
Four, $.getjson (Url,[data],[callback])
Copy Code code as follows:
$.getjson ("data.php", $ ("#firstName. Val ()"), function (Jsondata) {
$ ("#getJSONResponse"). HTML (jsondata.id); Without setting, the data type directly obtained is JSON,
So call needs to use the Jsondata.id method
);
When Ajax meets JQuery based applications are now growing, and for the foreground developer, it is not pleasant to deal directly with the HttpRequest at the bottom. Since jquery encapsulates JavaScript, it must have considered the problem of AJAX applications. Indeed, it would be easier to write Ajax in jquery than it would be to write it directly in JS. (Do not know with jquery long, will lose the knowledge of JS ...) This assumes that you are familiar with the jquery syntax to summarize some of the AJAX applications.
Load Static page
Load (URL, [data], [callback]);
URL address of the HTML page requested by the URL (String)
Data (MAP) (optional parameters) sent to the server Key/value
Callback (callback) (optional parameter) callback function when the request completes (does not need to be success)
The load () method can easily load static page content into the specified jquery object.
Copy Code code as follows:
$ (' #ajax-div '). Load (' data.html ');
In this way, the contents of the data.html will be loaded into the DOM object with the ID ajax-div. You can even implement AJAX operations that load portions of content by setting IDs, such as:
Copy Code code as follows:
$ (' #ajax-div '). Load (' data.html#my-section ');
Implement Get and Post methods
Get (URL, [data], [callback])
URL (String) to send the URL address of the request.
Data (MAP) (optional parameters) to be sent to the server, represented as a Key/value key-value pair, is QueryString appended to the request URL
Callback (callback) (optional parameter) the callback function (which is invoked only if response's return state is success) is loaded on success
Obviously this is a function that implements the Get method, and it's fairly simple to use.
Copy Code code as follows:
$.get (' login.php ', {
ID: ' Robin ',
Password: ' 123456 ',
Gate: ' Index '
}, function (data, status) {
Data is the returned object, status is the requested State
alert (data);
Now assume that the server script will return 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 to run when successful
});
Post (URL, [data], [callback], [type])
URL (String) to send the URL address of the request.
Data (MAP) (optional parameter) to be sent to the server in the form of a Key/value key value pair
Callback (callback) (optional parameter) the callback function (which is invoked only if response's return state is success) is loaded on success
Type (String) (optional parameter) request data types, Xml,text,json, etc.
is also a simple function of jquery, in fact
Copy Code code as follows:
$.post (' regsiter.php ', {
ID: ' Robin ',
Password: ' 123456 ',
Type: ' User '
},function (data, status) {
alert (data);
}, "JSON");
Event-Driven script load function: Getscript ()
Getscript (URL, [callback])
URL (String) to be loaded into the JS file address
Callback (function) (optional) After successfully loading the callback function
The Getscript () function can load JavaScript scripts remotely and execute them. This function can load the JS file across the domain (Magic ...?!). )。 The meaning of this function is huge, it can greatly reduce the amount of code that the page loads initially, because you can load the corresponding JS file according to the user's interaction, instead of loading it all when the page is initialized.
Copy Code code as follows:
$.getscript (' Ajaxevent.js ', function () {
Alert ("Scripts loaded!");
Loads the Ajaxevent.js and displays a dialog box prompt after successful loading.
});
Building a bridge for data communication: Getjson ()
Getjson (Url,[data],[callback])
URL (String) Send request address
Data (MAP) (optional) Key/value parameters to send
Callback (function) (optional) callback function when successfully loaded.
JSON is an ideal data transmission format that blends well with JavaScript or other host languages and can be used directly by JS. Using JSON to send "naked" data directly via get and post is more logical and more secure. As for the Getjson () function of jquery, just a simplified version of the Ajax () function that sets the JSON parameter. This function can also be used across domains, compared to get (), post () has some advantages. In addition, this function allows the program to execute the callback function X by writing the request URL in "myurl?callback=x" format.
Copy Code code as follows:
$.getjson (' feed.php ', {
Request:images,
ID:001,
Size:large
}, function (JSON) {
alert (Json.images[0].link);
Here JSON is a remote-returned JSON object, assuming the following format:
{' Images ': [
{link:images/001.jpg, x:100, y:100},
{link:images/002.jpg, x:200, y 200:}
//]};
}
);
More low-level Ajax () functions
Although the get () and post () functions are very simple and easy to use, they are not achievable for more complex design requirements, such as making different moves at different times of the Ajax delivery. jquery provides a more specific function: Ajax ().
Ajax (Options)
Ajax () provides a large amount of parameters, so you can achieve fairly complex functionality.
Name of parameter |
Type |
Describe |
Url |
String |
(Default: Current page address) sends the requested address. |
Type |
String |
(Default: "Get") Request method ("POST" or "get"), default to "get". Note: Other HTTP request methods, such as put and DELETE, are also available, but only partially supported by browsers. |
Timeout |
Number |
Sets the request timeout (in milliseconds). This setting overrides the global setting. |
Async |
Boolean |
(Default: TRUE) The default setting is that all requests are asynchronous requests. If you need to send a sync request, set this option to false. Note that the synchronization request will lock the browser and the user's other actions must wait for the request to complete before it can be executed. |
Beforesend |
Function |
You can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header.
The XMLHttpRequest object is the only parameter. function (XMLHttpRequest) {this;//the options for this Ajax request} function (XMLHttpRequest) {this;//the options For this AJAX request}
|
Cache |
Boolean |
(default: TRUE) JQuery 1.2 new functionality, set to false will not load request information from the browser cache. |
Complete |
Function |
The callback function (called when the request succeeds or fails) after the request completes.
Parameters: XMLHttpRequest Object, Success message 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") the content encoding type when sending information to the server. Default values are appropriate for most applications. |
Data |
Object, String |
Data sent to the server. is automatically converted to the request string format. The GET request is appended to the URL. View the ProcessData option description to prevent this automatic conversion. Must be in the Key/value format. If you are an array, JQuery will automatically correspond to the same name for different values. such as {foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2′. |
DataType |
String |
The type of data expected to be returned by the server. If not specified, JQuery will automatically follow the HTTP package MIME information Returns the Responsexml or ResponseText and passes as a callback function parameter, available values:"XML": Returns an XML document that can be processed with jQuery. HTML: Returns plain text HTML information, including script elements. Script: Returns the plain text JavaScript code. Results are not automatically cached. "JSON": Returns JSON data. "JSONP": Jsonp format. When calling a function using the JSONP form, Like "myurl?callback=?" JQuery will automatically replace? To the correct function name to execute the callback function. |
Error |
Function |
(Default: Automatic judgment (XML or HTML)) This method is called when a request fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being caught. function (XMLHttpRequest, textstatus, Errorthrown) {//typically Textstatus and Errorthown only one of them has a value of this;//the options for this a Jax Request} function (XMLHttpRequest, textstatus, Errorthrown) {//typically Textstatus and Errorthown only one of them has a value of this;//the Opti ONS for this AJAX request} |
Global |
Boolean |
(default: TRUE) triggers a global AJAX event. Set to false will not trigger global AJAX events. such as Ajaxstart or Ajaxstop. Can be used to control different AJAX events |
Ifmodified |
Boolean |
(default: false) gets new data only when the server data changes. Use HTTP packet last-modified header information to determine. |
ProcessData |
Boolean |
(default: TRUE) by default, the data sent is converted to an object (technically not a string) To match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert. |
Success |
Function |
callback function after successful request. This method has two parameters: the server returns the data, returns the status function (data, textstatus) {//data could be xmldoc, jsonobj, HTML, text, etc ... this;//the options for this Ajax requ EST} function (data, textstatus) {//data could be xmldoc, jsonobj, HTML, text, etc ... this;//the options for this AJA X Request} |
You can specify XML, script, HTML, JSON as its data type, you can set up processing functions for Beforesend, error, sucess, complete, and many other parameters can be customized to completely define the user's Ajax experience. In the following example, we use Ajax () to invoke an XML document:
Copy Code code as follows:
$.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, and you can search for nodes in it with Find (), next (), or XPath.
and using jquery to manipulate HTML objects is no different
}
});
Learn more about AJAX events
Some of the methods discussed earlier have their own event-handling mechanisms, which can only be said to be local functions from the page as a whole. jquery provides the definition of AJAX global functions to meet special requirements. Here are all the functions that jquery provides (listed in the order in which they are triggered):
Ajaxstart
(global event) starts a new AJAX request, and no other AJAX request is in progress at this time
Beforesend
(local event) triggered when an AJAX request starts. If you want, you can set the XMLHttpRequest object here
Ajaxsend
Global event that is triggered before the request starts (global event)
Success
(local event) is triggered when a request succeeds. That is, the server does not return an error, and the returned data is not error
Ajaxsuccess
Global Event Global Request succeeded
Error
(local event) is triggered only if an error occurs. You cannot execute both success and error two callback functions at the same time
Ajaxerror
Triggered when an error occurs globally for global events
Complete
(local event) Whether you request success or failure, even if the synchronization request, you can trigger the event when the request completes
Ajaxcomplete
triggered when a global event global request completes
Ajaxstop
(global event) triggers when no Ajax is in progress
Local events are described in previous functions, and we mainly look at global events. Global event monitoring for an object, the global Ajax action, will have an impact on it. For example, when the page is in Ajax operation, the DIV with the id "loading" is displayed:
Copy Code code as follows:
$ ("#loading"). Ajaxstart (function () {
$ (this). Show ();
});
Global events can also help you write global errors corresponding and successful accordingly, without requiring separate settings for each AJAX request. It is important to note that the parameters of global events are useful. In addition to Ajaxstart, Ajaxoptions, other events have event, XMLHttpRequest, ajaxoptions three parameters. The first parameter is the event itself, the second is the XHR object, and the third is the Ajax parameter object you pass. Displays the global AJAX situation in an object:
Copy Code code as follows:
$ ("#msg"). Beforesend (function (e,xhr,o) {
$ (this). HTML ("requesting" +o.url);
}). ajaxsuccess (function (e,xhr,o) {
$ (this). HTML (o.url+ "request succeeded");
}). ajaxerror (function (e,xhr,o) {
$ (this). HTML (o.url+ "request Failed");
});
Obviously, the third parameter can also help you pass the custom parameters you added to the Ajax event. In a single AJAX request, you can set the global value to False to make this request independent of the Ajax global event.
Copy Code code as follows:
$.ajax ({
URL: "request.php",
Global:false,
Disables global Ajax events.
});
If you want to set parameters for global Ajax, you will use the Ajaxsetup () function. For example, all AJAX requests are passed to request.php, the global method is disabled, and the Post method is enforced:
Copy Code code as follows:
$.ajaxsetup ({
URL: "request.php",
Global:false,
Type: "POST"
});
Some way you have to know.
Writing Ajax is certainly inseparable from getting the corresponding value from the page. Here are some simple ways to enumerate:
Val ()
The Val () function returns the value of the form's build, such as the value of any kind of input. With the selector operation, you can easily get the values of the option group, the Input box, the button, and so on.
Copy Code code as follows:
$ ("Input[name= ' info ']:text"). Val ();
Returns the value of the text box with the name info
$ ("Input[name= ' Pass ']:p assword"). Val ();
Returns the value of the password box named Pass
$ ("Input[name= ' Save ']:radio"). Val ();
Returns the value of the single option whose name is save
Analogy
Serialize ()
The Serialize function can help you convert all the values of a Form object to a string sequence. This is handy if you want to write a request in get format.
Serializearray () is similar to serialize () except that it returns a JSON object.
PS: This site also provides several powerful JSON parsing, conversion and formatting tools for everyone to choose to use, I believe that the next JSON Format data processing will help:
Online JSON code inspection, inspection, landscaping, formatting tools:
Http://tools.jb51.net/code/json
Online Xml/json Convert to each other:
Http://tools.jb51.net/code/xmljson
JSON code online Format/beautify/compress/edit/Convert tools:
Http://tools.jb51.net/code/jsoncodeformat
C language Style/html/css/json code formatting Landscaping tool:
Http://tools.jb51.net/code/ccode_html_css_json