AJAX-related Knowledge summary

Source: Internet
Author: User

One. Ajax configuration
  • Open a URL request address (some configuration before sending the request)
    • [Request Way]:get Series: Get/delete/head,post series: Post/put
    • [Request Address]: We send a data request to the server through this address, the requested address is generally provided in the background (API interface documentation)
    • [Set Synchronous async]: Default is True async, set to False for synchronization
    • [user Name]: username
    • [User PASS]: password, some times the server to ensure security, only allow some users to be able to request through the server (we are now generally anonymous access), at this time we need xhr.open("GET","/userInfo",true); to provide a secure secret key
  • Monitor the change of AJAX status to achieve different business operations
    • Xhr.readystate:AJAX status
      • 0:unsend: Not sent, just started to create a complete Ajax instance, the initial state is 0
      • 1:opened: Opened, that is, the second step has been completed
      • 2:headers_received: The client has received the response header information returned by the server
      • 3.LOADING: The response body content returned by the server is in transit
      • 4.DONE: The response body content has been received by the client
    • Xhr.status:HTTP Status Code
      • by status code to know if the current HTTP thing is successful, and why it failed
      • [2 begins]: Rep succeeded
        • 200:ok
      • [3]: also represents success, but this success has undergone some special handling
        • 301:move permenently: In the new version of the HTTP protocol, it represents a permanent transfer (it represents a permanent redirect in the previous protocol version)
        • 302:move temporarily in the new version of the HTTP protocol, which represents a temporary transfer (it represents a temporary redirect in a previous protocol version, 307 represents a temporary redirect in the new version protocol) and "Server load Balancing"
        • 304:not Modified, which reads the data in the cache (a particularly important manual for site performance optimization: We tend to put static resource files (css/js/img do 304 cache)
      • [4]: Represents an error, and is generally a client-side error
        • 400:bad request, requesting parameter error
        • 401:unauthorized: No access
        • 403:FO Rbidden: The request is received, but no normal result is returned, the cause of the error is not returned, and sometimes the 404
        • 404:not Found is returned, the requested address does not exist
        • 413:request Entity Too La Rge, the content that the client passes to the server exceeds the range that the server is willing to accept
      • [5]: Represents an error, and is generally a server-side error
        • 500:internal server errors, service Unknown error
        • 503:service unavailable, server overload
  • Operation
    • Xhr.response: Get response body (typically not used)
    • Xhr.responsetext: Gets the response body content, and gets the contents of the text Format (string):
    • Xhr.responsexml: Gets the response body content, and gets the contents of the XML format (XML document)
    • Xhr.getresponseheader ([key]): Gets the response header information, key is the keyword, such as date to get the time of the server
    • Xhr.getallresponseheader: Get all the response header information
    • Xhr.timeout: Sets the time-out for the AJAX request, if the current request exceeds this time, represents a timeout, the AJAX request ends, and the OnTimeOut event is triggered
    • Xhr.abort (): Interrupts the current AJAX request and can trigger the Onabort event
    • Xhr.setrequsetheader ([Key],[value]): Set Request header information
      • You must ensure that the open is executed before setting the request header
      • The content of the request header cannot be set to Chinese (unless encoded)
Two. Ajax Request send

The AJAX request is not started until after the send has been executed (before it is prepared), when the readystate=4 is over

    • Xhr.send (NULL): What is written in the Send method is the content that the client passes to the server through the request principal and does not want to pass the content through the request body we write null
Three. JS encoding and decoding

If you want to pass the Chinese characters to the server through the request header, we need to encode the contents of the message and then encode it by the server.

    • Escape/unescape: This method is often applied to the client to encode Chinese characters and special characters (generally not used, because the server-side language, except node other seemingly do not support this method)
    • Encodeuri/decodeuri: Decoding by Unicode encoding
    • Encodeuricomponent/decodeuricomponent: The special characters can also be encoded relative to the above method, while encodeURI can only encode Chinese characters
      • The server side is accepted and then decoded decodeuricomponent
Four. Encryption

Encryption is not a simple encoding and decoding, but is encrypted and decrypted according to the rules (important information in the project we usually have to encrypt)

    • [Reversible encryption]
      • Important information can be decrypted after encryption, such as: Phone number or bank card number to encrypt
      • General companies are writing their own encryption and decryption rules
    • [Irreversible encryption]
      • Encryption will not be decrypted, for example: all passwords are irreversible encryption
      • The most common is md5,sha1 ....
      • MD5 encrypted results are processed two or more times in a real project
Five. Get/post Series request

Regardless of the HTTP request, the client can pass the information to the server and the server can return the content to the client

  • Get series

    • Get: Get, give less to the server, take more from the server
    • Delete: Remove, delete some resource files from the server
    • Head: Gets the response header, which can only get the server's response header information and not get the response body content
  • Post series

    • POST: Push, give the server more, take less from the server
    • Put: Put in and put some resource files on the server
  • There are some major differences between the Get series and the Post series

      • The GET request is passed to the server content through the "question mark argument", the post series to the server content through the "request Body"
      • Each browser for the length of the URL is a maximum limit (Google 8kb/Firefox 7kb/ie2kb), if the POST request also with a question mark, it is likely to cause the length of the URL beyond the limit (post delivery of more content), the part will be automatically intercepted by the browser, resulting in incomplete information, So the post should use the request body, get can use the question mark to pass the parameter (get delivery less); The content size of the request body is not limited theoretically, in order to guarantee the speed of uploading in real project, we usually limit its size (for example, the upload file requirement is limited to 100KB)
    [get]xhr.open ( "GET", null) ; [Post]xhr.open ( "POST",  "/userinfo"); Xhr.send (" name=zxt&age=27&sex=1 ")        
      • The Get series request will have an uncontrolled cache, and the POST request will not
        • The reason is because get is passed to the server through the question mark, if I send two requests, the address and pass parameters are all the same, it will trigger the browser memory recognition function, it thinks that the second time you request data and the first time, so the data in the cache will be returned; such as the need to obtain stock information at any time we need to clear the cache of GET requests;
        • [clearing the cache only needs to add a random number after each requested address, guaranteeing that the address of each request is not exactly the same; property names are used in order not to conflict with other meaningful property names (industry specification)]
        xhr.open("GET","/userInfo?_="+Math.random());xhr.send(null);
      • Get series requests are not secure in relation to post requests, there is no absolute security in front of the internet, we usually surf the internet in bare-Ben
        • Cause: Get the content of the server is on the URL (question mark), there is a relatively simple hacker technology "URL hijacking", others can be hijacked by the URL of the data we pass to the server to capture the
        • As long as the message to the server is important information, no matter how much should use post
Six. Get server time
    • We get the server time and the current real time, there are some gaps "time difference", we get when the server returns data, the client will take a little time to receive the data, so when the client received this value, it has been a bit from the real time difference
      • Reduce the time difference
        1. Get server time at this stage of xhr.readystate==2 (Ajax requests must be asynchronous, synchronous only when status is 4)
        2. Xhr.open ("HEAD" ...) The request method is head request, we just need to get the response header
        3. The head request generates a cache problem, using math.random ();
        4. Simply use an AJAX request to increment the time in the acquisition to synchronize the server's time and reduce the pressure on the server
Seven. The Ajax in JQ
$.ajax("note.txt",{    method:"get",    dataType:"txt",    async:true,    cache:false,    data:{        name:"zxt",        age:"[27,28]"    }    success:function(){},    error:function(){},    complete:function(){}})
    • Method: equals the Type attribute
    • Datatype:txt (default), pre-set the format of the server return data, regardless of what value we set, the data returned to us by the server is generally a string or XML format, the purpose of the component library is based on the value we set to convert the results returned by the server to what we need to " The value of DataType "does not affect the server's return results
    • Async: Set synchronous or asynchronous, default is True, async
    • Cache: If the request of the current period is the Get series, we set or false, we need to clear the cache of GET request at this time, the default value True
    • Data
      • All the content that needs to be passed to the server is placed in data, the Get series takes the question mark, the Post series uses the request body, and the string content in data is what we pass on.
      • It can also be an object, the post series will put this object directly in the request body processing, what is put in the data is what; The Get series will split it xxx=xxx this form, placed at the end of the URL with a question mark passed to the server, it is worth noting that for Chinese characters and special characters, we need to encode the content
    • Complete: Regardless of success or failure, this will be done as soon as it is completed.
Eight. Simulation of the JQ in Ajax
    • Thought
      • Pass in as an object, avoiding sequence problems leading to parameter confusion
      • Default action on passed-in parameters
        • Use method to default, do not use type
      • Overwrites the passed-in object with default values, passes the default value, passing the value that you need to walk away
        • Unify type and method, and finally use method
      • Send an AJAX request
        1. Compatible processing of XMLHttpRequest
        2. In the onReadyStateChange incident, a discussion of the situation
          • Request failed
          • Request succeeded
            • To discuss the situation of readystate
            • Gets the response body content (typically a string), processing the response body content according to the datatype value, processing failure, empty result, avoiding error
            • Discuss the corresponding callback function and pass in the response body execution function
              • This is the XHR object in the callback function
        3. The data parameter is processed according to the method and passed in Send ()
      • Cache cleanup operations based on datatype and cache values
        • Verify that the URL is present, to add random numbers to the URL

AJAX-related Knowledge summary

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.