$. Get (), $. post (), $. ajax (), $. getJSON () in Jquery

Source: Internet
Author: User
Tags getscript
This article is about $. get (), $. post (), $. ajax (), $. the usage of getJSON () is summarized in detail. If you need it, you can refer to it for help. 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])

The Code is as follows:


$. GetJSON ("data. php", $ ("# firstName. val ()"), function (jsonData ){

$ ("# GetJSONResponse" ).html (jsonData. id);} // the data type directly obtained is json,
Therefore, jsonData. id must be used 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) 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.

The Code is as follows:


('{Ajax-p'{.load('data.html ');


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

The Code is as follows:


('{Ajax-p'{.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: '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.

The Code is as follows:


$. Post ('regsiter. php ',{
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.

The Code is as follows:


$. 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.

The 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 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 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 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.

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 ',
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:

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 ){
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.

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, 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.

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 ();
// 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 () is 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.