The solution to the use and caching of Ajax in jquery

Source: Internet
Author: User
Tags error handling http request json string format browser cache
This article mainly introduces the use of Ajax in jquery and the solution to the problem of caching. Need a friend can come over the reference, I hope to help you 1:get access browser that is idempotent is a same URL only one result [the same is the entire URL string exactly match] so the second visit if the URL string does not change the browser is directly taken out of the first visit Results   Post is considered to be a variable access (browsers think that the Post's submission must be changed)   prevent get's idempotent access just after the URL? +new Date ();   Design a Web page with a different URL string for each visit.   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 the Post method is used, the browser sends each form field element and its data as the entity content of the HTTP message to the Web server instead of being passed as the parameter of the URL address. 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 of data small, high processing efficiency, low security, will be cached, and post instead.   Using GET method need to note: 1 The parameters that are passed are processed by the encodeURIComponent method for get requests (or where the parameters are passed to the URL). Example: var url = "Update.php?username=" + encodeURIComponent (username) + "&content=" +encodeuricomponent   (content) + "&id=1";   Use POST method need to note: 1. Set header Context-type to application/x-www-form-urlencode ensure server knowledgeThere are parameter variables in the path entity. Usually use the setRequestHeader ("Context-type", "application/x-www-form-urlencoded;") of the XMLHttpRequest object. Example:   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?   Abc&sex=man&age=18 and 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   generated garbled reason: 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 the server side is gb2312 or other encoded data will generate garbled   solutions are: 1, if the client is GB2312 encoding, the server specified output stream encoding 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 already done the above method, or return garbled words, check whether you are getting, for get requests (or where the URL is involved in passing parameters), the passed parameters are first encodeURIComponent method of processing. If you don't use EncodeuricompOnent processing words, will also produce garbled.     Copy code code as follows: $.ajax not cached version: $.ajax ({             type: "Get"     URL : ' test.html ',     Cache:false,     dataType: "html",     success:function (msg) {  &NBSP ;     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 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.     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. (This I don't know very well)     parameter list: &nbsp   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 (milliseconds). This setting overrides the global setting.   Async  boolean (default: TRUE) The default setting is that 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 can modify functions of XMLHttpRequest objects before sending requests, 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) The new JQuery 1.2 feature, set to False, will not load request information from the browser cache.   Complete the callback function (called when the request succeeds or fails) after the  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. 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 for 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 expected 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 textstatus and Errorthown only one of them has a value     This The "Options for" Ajax request}  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) to get new data only when server data changes. Use HTTP packet last-modified header information to determine.   ProcessData  boolean (default: TRUE) by default, the number sentIt will be 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.   Success callback function after successful  function request. This method has two parameters: Server return data, return status   function (data, textstatus) { //data could be xmldoc, jsonobj, HTML, text, etc ... &nb Sp;this; The options for this Ajax request}    Here are several 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).   Please read the list of parameters carefully, if you want to use jquery for Ajax development, then these parameters you must be familiar with.     Sample code, get the blog home page article title:    code as follows: $.ajax ({  type: "Get",  URL: "Http://www.cnblogs.com/rss" ,  beforesend:function (XMLHttpRequest) { //showloading (); },  (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 () { //Requests for error handling  } });   Jquery.ajaxsetup (Options): Set global AJAX default options.   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:      code as follows: $.ajaxsetup ({  URL: "/xmlhttp/",  global:false,  type: " POST '  } ';  $.ajax ({data:mydata});    serialize () and Serializearray ()   serialize (): Sequence table table contents as characters String.   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& gt;  <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

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.