The use of ajax in jQuery and the solution of caching problems

  • 2020-03-30 01:01:03
  • OfStack

1:GET access browser thinks is idempotent
It's the same URL and there's only one result.
So on the second visit if the URL string doesn't change the browser simply pulls out the result of the first visit

POST is considered a mutable access (the browser thinks that the POST's submission must have changed)

To prevent idempotent access to GET by adding, right? + new Date (); , [so that the URL string is different for each visit]

You should also follow this principle when designing WEB pages

2: I talk about the difference between Get and Post in Ajax

The Get method:
Get is used to transfer simple data, but the size is generally limited to 1KB, and the data is appended to the url to send (HTTP header transmission), that is, the browser attaches each form field element and its data to the resource path in the request line according to the format of url parameters. Another important point is that it is cached by the client's browser so that someone can read the client's data, such as account Numbers and passwords, from the browser's history. Therefore, in some cases, the get method can cause serious security problems.

Post:
When POST is used, the browser sends each form field element and its data to the Web server as the entity content of the HTTP message, rather than as the parameter of the URL address. The amount of data transferred by POST is much larger than that by GET.

In a word, the GET method will be cached due to its small amount of data, high processing efficiency and low security, while the POST method will be the opposite.

Note about using get:
1 for get requests (or those involving url passing parameters), the passed parameters are processed by the encodeURIComponent method. Username =" +encodeURIComponent(username) + "&content=" +encodeURIComponent

(content) + & id = "1";

Note about using Post:
1. Set the contexttype of header to application/x-www-form-urlencode to ensure that the server knows that there are parameter variables in the entity. ). Ex. :

XmlHttp. SetRequestHeader (" the content-type ", "application/x - WWW - form - urlencoded");
Var name=abc&sex=man&age=18, var name=update.php?

Abc&sex =man&age=18 and var name=? Abc&sex =man&age=18 is all wrong;
3. Parameters are sent in the Send(parameter) method, for example: xmlhttp.send (name); If it is a get mode, directly xmlhttp.send (null);

4. Server-side request parameters distinguish Get from Post. $username = $_GET["username"]; If post mode is used, $username = $_POST["username"];

AJAX garbled code problem

Causes of garbled codes:
1. The default character encoding of the data returned by XTMLHTTP is utf-8. If the client page is gb2312 or other encoding data, garrages will be generated
2. The default character encoding of post method submission data is utf-8. If the server is gb2312 or other encoding data, it will generate scrambled codes

Solutions include:
1. If the client is gb2312 code, the output stream code is specified in the server
2. Both the server side and the client side use utf-8 encoding

Gb2312: header (' the content-type: text/HTML. Charset = GB2312 ');

Utf8: header (' the content-type: text/HTML. Charset = utf-8 ');

Note: if you have already done the above method and still return a gargle, check if your method is get. For get requests (or any involving url passing parameters), the parameters passed must be processed by the encodeURIComponent method.


$.ajax No cached version :
$.ajax({
             type:"GET"
    url:'test.html',
    cache:false,
    dataType:"html",
    success:function(msg){
        alert(msg);
    }
       });

JQuery. Ajax (options) : loads remote data via HTTP request
This is the underlying AJAX implementation of jQuery. Easy to use high - level implementation see $. Get, $. Post, etc.
$.ajax() returns the XMLHttpRequest object it created. Most of the time you do not need to manipulate the object directly, but special cases can be used to manually terminate the request.

Note: if you specify the dataType option, make sure the server returns the correct MIME information (such as "text/ XML "from XML). Wrong MIME types can 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 converted back to GET.
$.ajax() has only one parameter: the parameter key/value object, which contains the configuration and callback function information. See below for detailed parameter options.

In jQuery 1.2, you can load JSON data across domains by setting the data type to JSONP. When calling a function in the JSONP form, such as "myurl? The callback =?" JQuery will automatically replace? Is the correct function name to execute the callback function. When the data type is set to "jsonp", jQuery will automatically call the callback function. I don't really understand this.

Parameter list:

The function (XMLHttpRequest) {
  This; // the options for this ajax request
}
Cache  Boolean (default: true) jQuery 1.2 new feature, set to false will not load request information from the browser cache.
Complete  Function callback Function after the request completes (called on success or failure of the request). Parameter: XMLHttpRequest object, a string of success messages.

Function (XMLHttpRequest, textStatus) {
  This; // the options for this ajax request
}
ContentType  String (default: "application/x-www-form-urlencoded") sends information to the server in a content-coded type. The default values are appropriate for most applications.
Data  Object,
String data sent to the server. Automatically converts to the request string format. A GET request is appended to the URL. See the description of the processData option to disable this automatic conversion. Must be in Key/Value format. If it is an array, jQuery will automatically assign different values to the same name. Such as {foo: [" bar1 ", "bar2"]} into '& 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 package MIME information and pass it as a callback function parameter. The available values are:

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

"HTML ": returns plain HTML information; Contains script elements.

"Script ": returns plain JavaScript code. The results are not automatically cached.

"Json ": returns json data.

"Jsonp ": jsonp format. When calling a function in the JSONP form, such as "myurl? The callback =?" JQuery will automatically replace? Is the correct function name to execute the callback function.

Error  Function (default: automatic determination (XML or HTML)) is called when the request fails. This method takes three arguments: the XMLHttpRequest object, the error message, and (possibly) the error object to be caught.

Function (data, textStatus) {
  // data could be xmlDoc, jsonObj, HTML, text, etc...
  This; // the options for this ajax request
}

There are several Ajax event parameters: beforeSend, success, complete, error. We can define these events to handle each of our Ajax requests well. Notice that the "this" in these Ajax events refers to the option information of the Ajax request (see the picture of the "this" when referring to the get() method).
Read the above list of parameters, which you must be familiar with if you are going to use jQuery for Ajax development.

Sample code to get the blog garden home page article title:


$.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 options.
Set the default address of the AJAX request to "/ XMLHTTP /", disable triggering of global AJAX events, and replace the default GET method with POST. Subsequent AJAX requests do not set any option parameters.

JQuery code:


$.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 JSON data structure data.

Example:
HTML code:


<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 articles: