Use of ajax in jQuery and solutions to cache Problems

Source: Internet
Author: User

Use of ajax in jQuery and solutions to cache Problems

This article describes how to use ajax in jQuery and how to solve the cache problem. For more information, see.

1: GET access to the browser is considered to be idempotent

It means that the same URL has only one result. [the same means that the whole URL string is exactly matched]

Therefore, if the URL string remains unchanged during the second visit, the browser directly obtains the result of the first visit.

 

POST is regarded as a variable access (the browser believes that the submission of POST must be changed)

 

To prevent idempotent GET access, add? + New Date ();, [in short, the URL string for each access is different]

 

This principle should also be followed when designing web pages

 

2: I. Differences between Ajax Get and Post

 

Get method:

The get method can be used to transmit simple data, but the size is generally limited to 1 kb, and the data is appended to the url for sending (http header transfer), that is, the browser attaches the form field elements and their data to the resource path in the request line according to the URL parameter format. The most important thing is that it will be cached by the client's browser, so that others can read the customer's data from the browser's historical records, for example, account and password. Therefore, in some cases, the get method may cause serious security problems.

 

Post method:

When the POST method is used, the browser sends the form field elements and their data to the Web server as the entity content of the HTTP message, rather than as the URL address parameter, the amount of data transmitted in POST mode is much larger than that transmitted in GET mode.

 

In short, the GET method delivers a small amount of data, high processing efficiency, low security, and will be cached, whereas the POST method does not.

 

Note the following when using get:

1 For get requests (or any request involving url-based parameters), The passed parameters must be processed by the encodeURIComponent method. For example: var url = "update. php? Username = "+ encodeURIComponent (username) +" & content = "+ encodeURIComponent

 

(Content) + "& id = 1 ";

 

Note the following when using Post:

1. set the Context-Type of the header to application/x-www-form-urlencode to ensure that the server knows that there are parameter variables in the object. the SetRequestHeader ("Context-Type", "application/x-www-form-urlencoded;") of the XmlHttpRequest object is usually used ;"). Example:

 

XmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");

2. the parameter is a key-value pair with one-to-one correspondence between names and values. Each pair of values is separated by an ampersand. for example, var name = abc & sex = man & age = 18. Note that var name = update. php?

 

Abc & sex = man & age = 18 and var name =? Abc & sex = man & age = 18 is incorrect;

3. the parameter is sent in the Send (parameter) method, for example, xmlHttp. send (name); if it is in get mode, xmlHttp. send (null );

 

4. Server Request Parameters are differentiated between Get and Post. For the get method, $ username = $ _ GET ["username"]; for the post method, $ username = $ _ POST ["username"];

 

AJAX garbled

 

Cause of garbled characters:

1. The default character encoding of data returned by xtmlhttp is UTF-8. If the client page is gb2312 or other encoding data, garbled characters are generated.

2. The default character encoding for data submitted by the post method is UTF-8. If the server side is gb2312 or other encoding data, garbled characters are generated.

 

Solutions:

1. If the client is gb2312 encoded, specify the output stream encoding on the server.

2. Both the server and client use UTF-8 encoding.

 

Gb2312: header ('content-Type: text/html; charset = GB2312 ');

 

Utf8: header ('content-Type: text/html; charset = UTF-8 ');

 

Note: If you have already followed the above method and returned garbled characters, check whether your method is get. For get requests (or any request involving url parameters ), the passed parameters must be processed by the encodeURIComponent method. if you do not use encodeURIComponent for processing, garbled characters are generated.

 

 

Copy the Code as follows:

$. Ajax non-Cache version:

$. Ajax ({

Type: "GET"

Url: 'test.html ',

Cache: false,

DataType: "html ",

Success: function (msg ){

Alert (msg );

}

});

 

 

JQuery. ajax (options): loads remote data through HTTP requests

This is the underlying AJAX Implementation of jQuery. For easy-to-use high-level implementation, see $. get, $. post, and so on.

$. Ajax () returns the created XMLHttpRequest object. In most cases, you do not need to directly operate on this object, but in special cases it can be used to manually terminate the request.

 

Note: If you specify the ype option, make sure that the server returns the correct MIME information (for example, xml returns "text/xml "). Incorrect MIME types may cause unpredictable errors. See Specifying the Data Type for AJAX Requests.

 

When the datatype type is set to 'script', all remote (not in the same domain) POST requests are switched to GET.

$. Ajax () has only one parameter: The parameter key/value object, which contains information about various configurations and callback functions. For detailed Parameter options, see.

 

In jQuery 1.2, you can load JSON data across domains. You need to set the data type to JSONP during use. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function. When the data type is set to "jsonp", jQuery automatically calls the callback function. (I don't quite understand this)

 

Parameter List:

 

Name type description

Url String (default: Current page address) the address of the request sent.

Type String (default: "GET") Request Method ("POST" or "GET"), default: "GET ". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but are only supported by some browsers.

Timeout Number sets the request timeout (in milliseconds ). This setting overwrites the global setting.

Async Boolean (default: true) All requests are asynchronous requests by default. 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.

Before sending a request, the beforeSend Function 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.

The callback Function after the complete Function 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

}

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

The data type that the dataType String expects to return from 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": returns an XML document, which 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, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function.

 

This method is called when an error Function (default: Automatic judgment (xml or html) request fails. This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object.

 

Function (XMLHttpRequest, textStatus, errorThrown ){

// Generally, textStatus and errorThown have only one value.

This; // the options for this ajax request

}

Whether global Boolean (default: true) triggers a global AJAX event. Setting false does not trigger global AJAX events, such as ajaxStart or ajaxStop. Can be used to control different Ajax events

IfModified Boolean (default: false) obtains 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.

Callback Function after successful success Function 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

}

 

There are several Ajax event parameters: beforeSend, success, complete, and error. We can define these events to process every Ajax request. Note that this in these Ajax events points to the option Information of the Ajax request (see the image of this in the get () method ).

Read the parameter list carefully. If you want to use jQuery for Ajax development, you must be familiar with these parameters.

 

Sample Code to obtain the topic of the blog homepage:

 

The Code is as follows:

$. Ajax ({

Type: "get ",

Url: "http://www.cnblogs.com/rss ",

BeforeSend: function (XMLHttpRequest ){

// ShowLoading ();

},

Success: function (data, textStatus ){

$ (". Ajax. ajaxResult" ).html ("");

$ ("Item", data). each (function (I, domEle ){

$ (". Ajax. ajaxResult "). append ("<li>" + $ (domEle ). children ("title "). text () + "</li> ");

});

},

Complete: function (XMLHttpRequest, textStatus ){

// HideLoading ();

},

Error: function (){

// Handle request errors

}

});

 

JQuery. ajaxSetup (options): sets the global AJAX default options.

Set the default address of an AJAX request to "/xmlhttp/". Do not trigger a global AJAX event. Use POST instead of the default GET method. No option parameters are set for subsequent AJAX requests.

 

JQuery code:

 

The Code is as follows:

$. AjaxSetup ({

Url: "/xmlhttp /",

Global: false,

Type: "POST"

});

$. Ajax ({data: myData });

 

Serialize () and serializeArray ()

Serialize (): the content of the sequence table is a string.

SerializeArray (): serialize table elements (similar to the '. serialize ()' method) to return JSON data structure data.

 

Example:

HTML code:

 

 

Copy the Code as follows:

<P id = "results"> <B> Results: </B> </p>

<Form>

<Select name = "single">

<Option> Single </option>

<Option> Single2 </option>

</Select>

<Select name = "multiple" multiple = "multiple">

<Option selected = "selected"> Multiple </option>

<Option> Multiple2 </option>

<Option selected = "selected"> Multiple3 </option>

</Select> <br/>

<Input type = "checkbox" name = "check" value = "check1"/> check1

<Input type = "checkbox" name = "check" value = "check2"

Checked = "checked"/> check2

<Input type = "radio" name = "radio" value = "radio1"

Checked = "checked"/> radio1

<Input type = "radio" name = "radio" value = "radio2"/> radio2

</Form>

 

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.