Sharp jQuery Reading Notes --- Ajax in jQuery -- get, post, and other methods, jquery --- jquery

Source: Internet
Author: User
Tags getscript

Sharp jQuery Reading Notes --- Ajax in jQuery -- get, post, and other methods, jquery --- jquery


The load () method is usually used to obtain static data files from the Web server. However, this does not reflect the full value of ajax.

In a project, if you need to pass some parameters to the page on the server, you can use the $. get () or $. post () method (or the $. ajax () method)

The $. get () method uses the GET Method for asynchronous requests. Structure: $. get (url [, data] [, callback] [, type])

$. Get () method parameters are described as follows:

Parameter Name Type Description
Url String URL of the requested HTML page
Data (optional) Object The key/value data sent to the server will be appended to the request URL as QueryString.
Callback (optional) Function When the load is successful, the callback function (this method is called only when the return status of Response is success) automatically passes the request results and status to this method.
Type (optional) String The format of the content returned by the server, including xml, html, script, json, text, and _ default.

$. Post () method.

The structure and usage of the $. post () and $. get () methods are the same, but there are still the following differences between them:

  • The GET request will pass the parameters following the URL, while the POST request will be sent to the Web server as the entity content of the HTTP message.
  • The GET method has a limit on the size of the transmitted data (usually not greater than 2 kb), while the data transmitted using the POST method is much larger than the GET method (theoretically unlimited)
  • The data requested by the GET method is cached by the browser, so others can read the data from the browser's historical records, such as accounts and passwords. In some cases, the GET method may cause serious security problems, while the POST method can avoid these problems.
  • The GET and POST methods also obtain different data on the server.

 

$. GetScript (): jQuery provides this method to directly load js files. It is as simple and convenient as loading an HTML segment and does not need to process JavaScript files. JavaScript files are automatically executed.

The jQuery code is as follows:

$(function () {        $("#send").click(function () {            $.getScript("test.js");        });})

Like other ajax methods, the $. getScript () method also has a callback function, which runs after the JavaScript file is loaded successfully.

For example, if you want to load the jQuery official color animation plug-in (jquery. color. js), bind the color change animation to the element after successful loading:

<! DOCTYPE html> 

 

$. GetJson (): This method is used to load JSON files. It is used in the same way as $. getScript.

<! DOCTYPE html> 

The test. json file is:

[{"Username": "zhangsan", "content": "sofa. "},{" username ":" Li Si "," content ":" bench. "},{" username ":" Wang Wu "," content ":" floor. "}]

 

The JSONP callback function is used to load JSON data of other websites. For example:

<! DOCTYPE html> 

Note:

  • JQuery will automatically put the callback function in the URL, such as "url? Callback =? "The last one in "? "Replace it with the correct function name to execute the callback function.
  • JSONP (JSON with Padding) is an unofficial protocol that allows the server to integrate Script tags to return to the client and implement cross-origin access through JavaScript Callback. JSON is a plain text that contains simple brackets, so many channels can exchange JSON messages. Due to the restrictions of the same-origin policy, developers cannot use XMLHttpRequest for communication on external servers. JSONP is a method that can bypass the same-source policy, that is, by using the combination of JSON and <script> tags, the server directly returns executable JavaScript function calls or JavaScript objects. Currently, JSONP has become the preferred choice for cross-origin Web applications of major companies.

$. Ajax () is the underlying ajax Implementation of jQuery. Its structure is as follows:

$. Ajax (options ). this method has only one parameter, but this object contains $. the request settings and callback functions required by the ajax () method. parameters exist in the form of key/value. All parameters are optional,

The list of common parameters is as follows:

Parameter Name Type Description
Url String (The current page address by default) the address for sending the request
Type String The request method (post or get) is get by default. Note that other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support
Timeout Number Set the request timeout (in milliseconds ). This setting overwrites the global settings of the $. ajaxSetup () method.
Data Object or String The data sent to the server. If it is not a string, it is automatically converted to the string format. The GET request will be appended to the url. To prevent this automatic conversion, you can view the processData option. The object must be in the key/value format. For example, {foo1: "bar1", foo2: "bar2"} is converted to & foo1 = bar1 & foo2 = bar2. 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. The available types are as follows.

Xml: the XML document is returned and can be processed by jQuery.

Html: returns plain text HTML information. The script tag is executed when the DOM is inserted.

Script: returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note that during remote requests (not in the same domain), all POST requests will be converted to GET requests.

Json: Return JSON data

Jsonp: JSONP format. When calling a function in the form of JSONP, such as myurl? Callback = ?, JQuery will automatically Replace the last "? "For the correct function name to execute the callback function.

Text: returns a plain text string.

BeforeSend Function

Before sending a request, you can modify the function of the XMLHttpRequest object, for example, adding a custom HTTP header. In beforeSend, if false is returned, the Ajax request can be canceled. The XMLHttpRequest object is a unique parameter.

Function (XMLHttpRequest ){

This; // The options parameter passed when calling this Ajax request

}

Complete Function

Callback Function called after the request is complete (called when the request is successful or fails)

Parameter: XMLHttpRequest object and a string that describes the successful request type.

Function (XMLHttpRequest, textStatue ){

This; // The options parameter passed when calling this Ajax request

}

Success Function

The callback function called after the request is successful. There are two parameters.

(1) data returned by the server and processed according to the dataType Parameter

(2) A string describing the status

Function (data, textStatus ){

// Data may be xmlDoc, jsonObj, html, text, etc.

This; // The options parameter passed when calling this Ajax request

}

Error Function

The function called when the request fails. This function has three parameters: XMLHttpRequest object, error message, and captured error object (optional ).

Ajax event functions are as follows:

Function (XMLHttpRequest, textStatus, errorThrown ){

// Generally, textStatus and errorThrown only contain one of the information.

This; // The options parameter passed when calling this Ajax request

}

Global Boolean

The default value is true. Indicates whether to trigger a global Ajax event. Setting false does not trigger global Ajax events. AjaxStart or AjaxStop can be used to control various Ajax events.

Other highlights

JQuery tutorial (29)-jQuery plug-in development-Specify parameters for plug-in Methods jQuery tutorial (28)-jQuery plug-in development-jQuery tutorial (27) -jQueryajax-Modify default options jQuery tutorial (26)-ajax-use JSONP to load Remote Data jQuery tutorial (25)-security restrictions on ajax operations

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.