The use of Ajax in jquery and the solution of caching problem _jquery

Source: Internet
Author: User
Tags string format browser cache

1:get Access Browser thinks it's idempotent.
The same URL has only one result [the same is the exact match of the entire URL string]
So the second visit if the URL string does not change the browser is directly come up with the results of the first visit

Post is considered a variable access (the browser believes that the Post's submission must be changed)

To prevent the equal power access of Get on the URL after adding? +new Date ();, [in short, to make each access URL string different]

You should also follow this principle when designing Web pages.

2: I. Talking about the difference between get and post of Ajax

Get Way:
You can transfer simple data in Get mode, but the size is typically limited to 1KB, the data is appended to the URL (HTTP header transfer), that is, the browser appends individual form field elements and their data to the resource path in the request line in the format of the URL parameter. The most important point is that it is cached by the client's browser, so that other people can read the customer's data, such as account number and password, from the browser's history. Therefore, in some cases, the Get method poses a serious security problem.

Post method:
When using post, the browser sends individual form field elements and their data to the Web server as the entity content of the HTTP message, rather than as a parameter to the URL address, and the amount of data that is passed by post is much larger than the amount of data that is transmitted using the GET method.

In short, get-mode transfer data is small, high processing efficiency, low security, will be cached, and post instead.

You need to be aware of using get methods:
1 for Get requests (or any that involve passing parameters to the URL), the passed parameters are processed first by the encodeURIComponent method. Example: var url = "Update.php?username=" +encodeuricomponent ( username) + "&content=" +encodeuricomponent

(content) + "&id=1";

Use POST method to note:
1. Set header Context-type to Application/x-www-form-urlencode ensure that the server knows that there are parameter variables in the entity. Usually use the setRequestHeader ("Context-type", "application/x-www-form-urlencoded;") of the XMLHttpRequest object. Cases:

Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
2. The parameter is a name/value one by one corresponding to the key value pairs, each pair of values separated by the & number. like Var name=abc&sex=man&age=18, pay attention to Var name=update.php?

The abc&sex=man&age=18 and the Var name=?abc&sex=man&age=18 are all wrong;
3. Parameters sent in the Send (parameter) method, example: Xmlhttp.send (name); If it is a get way, direct xmlhttp.send (NULL);

4. Server-side request parameters differentiate get and post. If the Get method is $username = $_get["username"]; If it is the POST method, then $username = $_post["username"];

Ajax garbled problem

The reason for the garbled:
1, Xtmlhttp returned the data default character encoding is Utf-8, if the client page is gb2312 or other encoded data will produce garbled
2, Post method submission data default character encoding is utf-8, if server-side is gb2312 or other encoded data will produce garbled

Solutions include:
1, if the client is gb2312 code, then specify the output stream code on the server
2, server-side and client are using UTF-8 encoding

Gb2312:header (' content-type:text/html;charset=gb2312 ');

Utf8:header (' Content-type:text/html;charset=utf-8 ');

Note: If you have done the above method, or return garbled words, check your way is get, for get requests (or where the URL is involved in passing parameters), the parameters are passed first encodeURIComponent method is processed. If not treated with encodeuricomponent, it will produce garbled characters.

Copy Code code as follows:

$.ajax Not cached version:
$.ajax ({
Type: "Get"
URL: ' test.html ',
Cache:false,
DataType: "HTML",
Success:function (msg) {
Alert (msg);
}
});


Jquery.ajax (options): Load remote Data via HTTP request
This is the underlying AJAX implementation of jquery. Simple and easy-to-use high-level implementation see $.get, $.post, etc.
$.ajax () returns the XMLHttpRequest object that it created. In most cases you do not need to manipulate the object directly, but in special cases you can use it to manually terminate the request.

Note: If you specify the DataType option, make sure that the server returns the correct MIME information (such as the XML return "Text/xml"). The wrong MIME type can cause unpredictable errors. See Specifying the Data Type for AJAX Requests.

When you set the DataType type ' script ', all remote (not in the same domain) post requests are converted back to get mode.
$.ajax () has only one parameter: The parameter Key/value object, which contains the configuration and callback function information. Detailed parameter options see below.

In JQuery 1.2, you can load JSON data across domains and use it to set the data type to JSONP. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function. When the data type is set to "Jsonp", JQuery automatically invokes the callback function. (I don't know this very well)

Parameter list:

Name Type description
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) is the default setting, 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 to modify XMLHttpRequest objects before sending a request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter.

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.
The callback function (called when the request succeeds or fails) after the complete function request completes. Parameters: XMLHttpRequest Object, Success message string.

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 sent to the server's data. 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 expects the data type returned by the server. If not specified, JQuery will automatically return Responsexml or responsetext based on the HTTP packet MIME information and pass 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 JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function.

This method is called when the error Function (default: Automatic judgment (XML or HTML)) fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being caught.

function (XMLHttpRequest, textstatus, Errorthrown) {
Typically, only one of the Textstatus and Errorthown has a value.
This The options for this AJAX request
}
Whether global Boolean (default: TRUE) triggers a globally AJAX event. Setting 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 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.
The callback function after a successful success function 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 request
}

Here are a few Ajax event parameters: Beforesend, Success, complete, error. We can define these events to deal well with each of our AJAX requests. Notice that this in these AJAX events is the information about the options for the Ajax request (refer to the picture of this when you say Get () method).
Read the argument list carefully, and if you want to use jquery for AJAX development, you need to be familiar with these parameters.

Sample code to get the title of the article on the home page of the blog:

Copy Code code 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 () {
Request Error Handling
}
});

Jquery.ajaxsetup (Options): Sets the global AJAX default option.
Set AJAX request default address is "/xmlhttp/", prohibit triggering global Ajax event, use POST instead of default get method. Subsequent AJAX requests no longer have any option parameters set.

JQuery Code:

Copy Code code as follows:

$.ajaxsetup ({
URL: "/xmlhttp/",
Global:false,
Type: "POST"
});
$.ajax ({data:mydata});

Serialize () and Serializearray ()
Serialize (): Sequence table table contents are strings.
Serializearray (): Serializes the Table element (similar to the '. Serialize () ' method) to return the JSON data structure.

Example:
HTML code:

Copy Code 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>

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.