Summary of usage of $.get (), $.post (), $.ajax (), $.getjson () in jquery

Source: Internet
Author: User
Tags event listener getscript browser cache

This article is for jquery in $.get (), $.post (), $.ajax (), $.getjson () with a detailed summary of the introduction, the need for friends can come over to the reference, I hope to be helpful to everyone

Read more about Jquery's various Ajax functions:
$.get (), $.post (), $.ajax (), $.getjson ()

a, $.get (url,[data],[callback])

Description: URL is the request address, data is the list of request data, callback is the callback function after the successful request, the function accepts two parameters, the first is the data returned by the server, the second parameter is the state of the server, is an optional parameter.

In this case, the format of the server return data is actually a string situation, not the JSON data format we want, in this reference just to compare the description

Copy CodeThe code is 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, has a type parameter, type is the requested data type, can be a type of html,xml,json, if we set this parameter To: json, then the returned format is in JSON format, if not set, and $. Get () returns the same format as the String.

Copy CodeThe code is as Follows:
$.post ("data.php", $ ("#firstName. val ()"), function (data) {

$ ("#postResponse"). HTML (data.name);

}, "json"//sets The type of get data, so the resulting data format is Json-type

);


sam, $.ajax (opiton)

Description: $.ajax () This function is powerful, you can do a lot of precise control of ajax, please refer to the relevant information for detailed description

Copy CodeThe code is 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 CodeThe code is as Follows:
$.getjson ("data.php", $ ("#firstName. val ()"), function (jsondata) {

$ ("#getJSONResponse"). HTML (jsondata.id);} Without setting, the data type is directly obtained as json,
So you need to use the Jsondata.id method when calling

);


When Ajax meets JQuery ajax-based applications are now more and more, and for Front-desk developers, it is not a pleasant thing to deal directly with the underlying Httprequest. Since jquery encapsulates JavaScript, it must have considered the problem of Ajax Applications. indeed, if using jquery to write Ajax would be more convenient than the direct use of JS write n times. (do not know the long with jquery, will not lose the knowledge of JS ...) This assumes that you are already familiar with the jquery syntax to summarize some of the applications of Ajax.

Loading static pages

Load (url, [data], [callback]);
URL address of the URL (String) of the requested HTML page
Data (Map) (optional Parameters) sent to the server Key/value
Callback (callback) (optional Parameter) callback function when the request is complete (does not need to be success)

The load () method can easily load static page content into a specified jquery Object.

Copy CodeThe code is as Follows:
$ (' #ajax-div '). load (' data.html ');
In this way, the contents of the data.html will be loaded into the DOM object with ID Ajax-div. You can even implement an AJAX operation that loads some content by making an id, such as:
Copy CodeThe code is as Follows:
$ (' #ajax-div '). load (' data.html#my-section ');
Implementing the Get and Post methods

Get (url, [data], [callback])
URL (String) to send the requested URL Address.
Data (Map) (optional Parameter) to be sent to the server, expressed as a key/value key-value pair, is appended to the request URL as QueryString
Callback (callback) (optional Parameter) the callback function when loading succeeds (only if the return state of response is success the method is Called)

Obviously this is a function that implements get mode, which is quite simple to use.

Copy CodeThe code is 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);
At this point, assume that the server script returns a text "hello, robin! ",
Then the browser will pop up a dialog box to display the paragraph text
Alert (status);
The result is success, error, and so on, but this is a function that will run when it succeeds.
});
Post (url, [data], [callback], [type])

URL (String) to send the requested URL Address.
Data (Map) (optional Parameter) to be sent to the server, expressed as a key/value key-value pair
Callback (callback) (optional Parameter) the callback function when loading succeeds (only if the return state of response is success the method is Called)
Type (String) (optional parameter) request data types, xml,text,json, etc.

is also a handy function of jquery, in fact the usage

Copy CodeThe code is as Follows:
$.post (' regsiter.php ', {
Id: ' Robin ',
Password: ' 123456 ',
Type: ' user '
},function (data, Status) {
Alert (data);
}, "json");
Event-driven Script Loader function: getScript ()

GetScript (url, [callback])
URL (String) to be loaded into the JS file address
Callback (function) (optional) After successful load callback function

The GetScript () function can be loaded remotely into JavaScript scripts and Executed. This function can be loaded into JS files across domains (magical ...!!). )。 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, without having to load it all when the page is Initialized.

Copy CodeThe code is as Follows:
$.getscript (' ajaxevent.js ', function () {
Alert ("Scripts loaded!");
Loads the Ajaxevent.js and displays a dialog prompt after a successful load.
});
Building a bridge for data communication: Getjson ()

Getjson (url,[data],[callback])
URL (String) to send the request address
Data (Map) (optional) key/value parameters to be sent
Callback (function) (optional) The callback function when loading SUCCEEDS.

JSON is an ideal data transmission format, It can be well fused with JavaScript or other host language, and can be used directly by js. Using JSON to send "naked" data directly through GET, post, is structurally more reasonable and more secure. As for Jquery's Getjson () function, It's just a simplified version of the Ajax () function that sets the JSON parameter. This function can also be used across domains, with a certain advantage over get () and post (). In addition, This function can be used to write the request URL as a "myurl?callback=x" format, so that the program executes the callback function X.

Copy CodeThe code is as Follows:
$.getjson (' feed.php ', {
request:images,
id:001,
Size:large
}, function (json) {
Alert (json.images[0].link);
Here JSON is the JSON object that is sent back remotely, assuming the following format:
{' Images ': [
{link:images/001.jpg, x:100, y:100},
{link:images/002.jpg, x:200, y 200:}
//]};
}
);
Lower-level Ajax () functions
Although the get () and post () functions are very simple and easy to use, some of the more complex design requirements are not achievable, such as making different moves during the different periods of time that Ajax SENDS. jquery provides a more specific function: Ajax ().

Ajax (options)
Ajax () provides a large amount of parameters, so you can implement quite complex functions.

Name of parameter Type Describe
Url String (default: Current page Address) sends the requested ADDRESS.
Type String (default: "get") The Request method ("POST" or "get"), the default is "get".
Note: other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it.
Timeout Number Sets the request time-out (in milliseconds). This setting overrides the global settings.
Async Boolean (default: True) by default, All requests are asynchronous Requests.
If you need to send a synchronization request, set this option to False.
Note that the sync 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 feature, set to False will not load the request information from the browser cache.
Complete Function The callback function after the request completes (called when the request succeeds or fails).

Parameters: 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") The content encoding type when sending information to the Server. The default values are suitable for most applications.
Data Object,
String
Data sent to the Server. is automatically converted to the request string Format. The GET request will be appended to the URL.
View the ProcessData option description to disallow this automatic Conversion. Must be a key/value format.
If an array, jQuery automatically corresponds to the same name for the different values.
such as {foo:["bar1", "bar2"]} is converted to ' &foo=bar1&foo=bar2′.
DataType String Expected data type returned by the Server. If not specified, JQuery will automatically be based on the HTTP packet MIME information
Returns Responsexml or responsetext, and is passed as a callback function parameter, with the available values:

"xml": returns an XML document that can be processed with jQuery.

Html: returns plain text HTML information, including the script Element.

"script": returns plain Text JavaScript Code. Results are not automatically cached.

"json": returns the JSON Data.

"jsonp": Jsonp Format. When a function is called using the JSONP form,

Like "myurl?callback=?" JQuery will be replaced automatically? is the correct function name to execute the callback Function.

Error Function (default: This method is called when a request for automatic judgment (xml or HTML) Fails.)

This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the Error object being Captured.

function (xmlhttprequest, textstatus, errorthrown) {//normally textstatus and Errorthown only one of which has the value of this; Jax request} function (xmlhttprequest, textstatus, errorthrown) {//normally textstatus and Errorthown only one has the value of This;//the Opti ONS for this Ajax request}
Global Boolean (default: True) whether to trigger global AJAX Events. Setting to False will not trigger a global AJAX Event.

such as Ajaxstart or ajaxstop. Can be used to control different AJAX events

Ifmodified Boolean (default: False) to get new data only when the server data changes.

Use the HTTP packet last-modified header information to Determine.

ProcessData Boolean (default: True) by default, the sent data 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

The callback function after the request SUCCEEDS. This method has two parameters: the server returns 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 the processing function for beforesend, error, sucess, complete and other states, and many other parameters can also be customized to completely define the User's Ajax Experience. In the following example, we use Ajax () to invoke an XML document:

Copy CodeThe code is 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, You can use Find (), next () or xpath, and other methods to find the node,
There is no difference between manipulating HTML objects with jquery
}
});
Learn more about AJAX events
Some of the methods discussed earlier have their own event handling mechanism, which can only be described as local functions from the overall page. jquery provides the definition of an AJAX global function to meet specific requirements. The following are all the functions provided by jquery (in The order of the triggering sequence below):

Ajaxstart
(global Event) starts a new Ajax request, and no other AJAX request is in progress at this time
Beforesend
(local Event) is triggered when an AJAX request Starts. If necessary, you can set the XMLHttpRequest object here
Ajaxsend
Global event triggered before the request starts (global Event)
Success
triggered when the request is successful (local event). 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 when an error occurs. You cannot perform both success and error two callback functions at the same time
Ajaxerror
Global event triggered when an error occurs globally
Complete
(local Event) Whether you request success or failure, even if the request is synchronous, you can trigger the event when the request is complete
Ajaxcomplete
triggered when global event global request completes
Ajaxstop
(global Event) triggered when no Ajax is in progress
Local events are described in previous functions, and we look at global events in the Main. A global event listener for an object will have an impact on the global Ajax Action. For example, when the page is doing an Ajax operation, the DIV with the ID "loading" is displayed:

Copy CodeThe code is as Follows:
$ ("#loading"). Ajaxstart (function () {
$ (this). Show ();
});
Global events can also help you write global errors appropriately and successfully accordingly, without having to set up independently for each Ajax Request. It is necessary to point out that the parameters of the global event 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 that you Passed. Displays the global Ajax situation in an object:
Copy CodeThe code is 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 value of global to false to make this request independent of the AJAX global Event.
Copy CodeThe code is 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, Pass all AJAX requests to request.php, disable the global method, and force the Post method to Pass:
Copy CodeThe code is as Follows:
$.ajaxsetup ({
Url: "request.php",
global:false,
Type: "POST"
});
Some of the ways you have to know
Ajax must be written to get the corresponding value from the Page. Here are some simple ways to enumerate:

Val ()
The Val () function can return the value of a form's build, such as the value of any kind of input. With the selector action, you can easily get the value of an option group, input box, button, and so On.

Copy CodeThe code is 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 a single option whose name is save
And so on
Serialize ()

The Serialize function can help you convert all the values of a Form object to a sequence of strings. This is handy if you want to write a get format Request.
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 for everyone to data processing will be helpful:

Online JSON code inspection, inspection, landscaping, formatting tools:
Http://tools.jb51.net/code/json

Online Xml/json Convert each other:
Http://tools.jb51.net/code/xmljson

JSON code online formatting/landscaping/compression/editing/conversion tools:
Http://tools.jb51.net/code/jsoncodeformat

C language Style/html/css/json code formatting beautification tool:
Http://tools.jb51.net/code/ccode_html_css_json

Summary of usage of $.get (), $.post (), $.ajax (), $.getjson () in jquery

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.