Native JS sends Ajax requests

Source: Internet
Author: User

Fallen for a while, today opened the blog, found that even login username and password are not remember. More than half of the 2016, can not be so wandering down.

Participated in the NetEase micro-front-end siege lion training, currently carried out to the big job development stage, feel difficult. However, no matter what the outcome, we must complete this task-after all, it is spent money, can not be wasted. So prepare to write a series of blog, the development process encountered a variety of small problems recorded, it is a start from beginning to end to do a development record it. Read through the development requirements, roughly do a bit of decomposition, intends to split into a small module, one by one. Today is the preparation stage, want to try to adjust the interface, to see if it can be adjusted.

Anyway Sending requests from the page to the server is, of course, an AJAX approach. Here we no longer pull the whole history, the concept, the direct start, all to the productivity on par. The jquery method is usually used to send AJAX requests, but no JS framework is allowed in the big job, so the native JS is used to send the request.

The following steps are summed up:

1. Setting up XMLHttpRequest objects

Note that there are compatibility issues here (different for IE7 and the following browsers), the implementation code is as follows:

1 <script>2     var  xmlHttp; 3     if (window. XMLHttpRequest) {4         new  XMLHttpRequest (); 5     } Else {//compatible with IE7 and the following browser versions 6         New ActiveXObject ("Microsoft.XMLHTTP"); 7     }8 </script>

2. Establish connection, send request and parameters

Here are some ways to use Ajax. In fact, the main Request.open () method. Requests are divided into "GET" and "POST" forms. "Get" is used to get some parameters returned by the server, while the "POST" method allows the user to modify some data on the server.

<script>/*             *open Method Explanation       * Build request  Total three parameters       * First parameter: Method used, GET  or  POST       * Second parameter: URL address       * Third parameter: synchronous mode  or  asynchronous, general set to True, asynchronous; default also asynchronous call               */ Request.open ("GET", "Http://study.163.com/webDev/dhuai",true);       /*        The *send method interprets       * Send parameters, which are generally for the post method. When you use the Get method, this parameter passes null or no       value */     request.send (null); </script>

3. Building response Information

The status of the server returned to judge, if successful, then get the data, follow-up matters. Here are the main request.readystate and request.status two properties to judge.

Request.readystate: The status code attribute, enumerated as follows:

0: Request uninitialized, Open has not been called

1: Server connection established, open has been called

2: The request has been received, that is, received the header information

3: In request processing, the response body is received

4: The request is complete and the response is ready, that is, the response is complete

Request.status: State value, more, at the end of the article post all the state value enumeration, where the code first.

<script> 2 Request.onreadystatechange =function() { 3if(request.readystate==4) {//Request Complete4if(request.status==200) {//OK, everything's fine .5vardata = Json.parse (Request.responsetext);//put the returned data in the database variable6if(data.success) {7 document.getElementById ("XXX"). InnerHTML =data.msg;8}Else { 9 document.getElementById ("XXX"). InnerHTML = "Error occurred:" +data.msg;10                 }11}Else {Alert ("Error occurred:" +request.status);13             }14         } 15     }</script>

At this point, a complete AJAX request has been sent, and the returned information has been processed. It uses the Json.parse method, which means parsing a string into a JSON object for use in a program. The complete code is as follows:

1<script>2     varxmlHttp;3     if(window. XMLHttpRequest) {4XmlHttp =NewXMLHttpRequest ();5}Else{6XMLHTTP =NewActiveXObject ("Microsoft.XMLHTTP");7     }8Request.open ("GET", "HTTP://STUDY.163.COM/FAFHFG",true);9Request.send (NULL);TenRequest.onreadystatechange =function() { One         if(request.readystate==4) { A             if(request.status==200) {  -                 vardata =Json.parse (request.responsetext); -                 if(data.success) { thedocument.getElementById ("XXX"). InnerHTML =data.msg; -}Else { -document.getElementById ("XXX"). InnerHTML = "Error occurred:" +data.msg; -                 } +}Else { -Alert ("Error occurred:" +request.status); +             } A         }  at     } -</script>

The pro-test is available, the first interface in the big job is adjusted, and the data is obtained. Sadly, Google is fine, but cross-domain interception occurs on Firefox. Firefox has a high security requirement, so there is this limitation. Tried several methods and did not resolve it. However, the work document says that cross-domain issues are not considered, so it is no longer a matter of concern.

Attached: State status value

100-continue the initial request has been accepted, the customer should continue to send the remainder of the request. (HTTP 1.1 new)
101-switching Protocols Server translates the client's request to another protocol (HTTP 1.1 new)

200-ok Everything is OK, the answer document for Get and post requests is followed.
The 201-created server has created the document, and the location header gives its URL.
202-accepted has accepted the request, but the processing has not been completed.
The 203-non-authoritative information document has returned normally, but some of the answer headers may be incorrect because a copy of the document is being used, non-authoritative (HTTP 1.1 new).
204-no Content does not have a new document, the browser should continue to display the original document. This status code is useful if the user refreshes the page on a regular basis and the servlet can determine that the user's document is new enough.
205-reset content is not new, but the browser should reset what it displays. Used to force the browser to clear the form input (HTTP 1.1 new).
206-partial Content client sends a GET request with a range header that the server has completed (HTTP 1.1 new)


300-multiple Choices Customer-requested documents can be found in multiple locations that are listed in the returned document. If the server wants to make a preference, it should be indicated in the location answer header.
301-moved permanently The document requested by the customer elsewhere, the new URL is given in the location header, and the browser should automatically access the new URL.
302-found is similar to 301, but the new URL should be treated as a temporary replacement, not a permanent. Note that the corresponding status information in HTTP1.0 is "Moved temporatily". When the status code appears, the browser can automatically access the new URL, so it is a useful status code. Note that this status code can sometimes be used with 301 substitutions. For example, if the browser mistakenly requests Http://host/~user (the trailing slash is missing), some servers return 301, and some return 302. Strictly speaking, we can only assume that the browser will automatically redirect only if the original request is get. See 307.
303-see other is similar to 301/302, except that if the original request is post,location, the redirect target document specified by the header should be fetched via get (HTTP 1.1 new).
The 304-not Modified client has a buffered document and issues a conditional request (typically providing a if-modified-since header indicating that the customer only wants to update the document than the specified date). The server tells the customer that the original buffered document can continue to be used.
305-use Proxy The document requested by the client should be extracted via the proxy server indicated by the location header (HTTP 1.1 is new).
307-temporary Redirect and 302 (Found) are the same. Many browsers incorrectly respond with 302 responsesmakeRedirect, even if the original request is post, even though it can actually be redirected only if the answer to the POST request is 303. For this reason, HTTP 1.1 has been added in 307 to allow for more cleanup of the region in several status codes: When a 303 response occurs, the browser can follow the redirected get and post requests, and if the 307 answer, the browser can only follow the redirect to the GET request. (HTTP 1.1 new)

400-bad Request appearsGrammarError.
401-unauthorized access denied, client attempts to unauthorized access by passwordProtectionThe page. A www-authenticate header is included in the answer, and the browser displays the user name/Password dialog box, and then makes a request again after filling in the appropriate authorization header. IIS defines a number of different 401 errors, which indicate a more specific cause of the error. These specific error codes are displayed in the browser, but are not displayed in the IIS log:
401.1-Login failed.
401.2-The server configuration caused the login to fail.
401.3-not authorized due to ACL restrictions on resources.
401.4-Filter Authorization failed.
401.5-ISAPI/CGI application authorization failed.
401.7– access is denied by the URL authorization policy on the WEB server. This error code is specific to IIS 6.0.
403-forbidden resource is not available. The server understands the customer's request, but refuses to process it. This is usually caused by the permissions set on the file or directory on the server. Forbidden Access: IIS defines a number of different 403 errors, which indicate a more specific cause of the error:
403.1-execution access is forbidden.
403.2-Read access is forbidden.
403.3-Write access is forbidden.
403.4-Requires SSL.
403.5-Requires SSL 128.
The 403.6-IP address is rejected.
403.7-Requires a client certificate.
403.8-site access is denied.
403.9-Excessive number of users.
403.10-Invalid configuration.
403.11-Password change.
403.12-Deny access to the mapping table.
403.13-The client certificate is revoked.
403.14-Reject directory list.
403.15-Client access permission exceeded.
403.16-Client certificate is not trusted or invalid.
403.17-The client certificate has expired or is not yet valid.
403.18-The requested URL cannot be executed in the current application pool. This error code is specific to IIS 6.0.
403.19-CGI cannot be executed for clients in this application pool. This error code is specific to IIS 6.0.
403.20-passport Login failed. This error code is specific to IIS 6.0.
404-not Found could not find the resource at the specified location. This is also a common answer.
404.0-(None) – No files or directories found.
404.1-Unable to access the WEB site on the requested port.
The 404.2-web service extension lockout policy blocks this request.
The 404.3-mime mapping policy blocks this request.

405-method not allowed request method (GET, POST, HEAD, DELETE, PUT, trace, etc.) does not apply to the specified resource, the HTTP verb used to access this page is not allowed (the method is not allowed) (HTTP 1.1 new)
406-not acceptable The specified resource has been found, but its MIME type is incompatible with the client specified in the Accpet header, the client browser does not accept the MIME type of the requested page (HTTP 1.1 new).
407-proxy authentication Required requires proxy authentication, similar to 401, to indicate that the client must be authorized by the proxy server first. (HTTP 1.1 new)
408-request Timeout The customer has not made any requests during the waiting time of the server license. Customers can repeat the same request at a later time. (HTTP 1.1 new)
409-conflict is usually associated with a put request. The request cannot succeed because the request conflicts with the current state of the resource. (HTTP 1.1 new)
410-gone the requested document is no longer available, and the server does notknowWhich address should be redirected to. It differs from 404 in that returning 407 means that the document has permanently left the specified location, and 404 indicates that the document is unavailable for unknown reasons. (HTTP 1.1 new)
The 411-length Required server cannot process the request unless the client sends a content-length header. (HTTP 1.1 new)
412-precondition Failed Some of the prerequisites specified in the request header failed (HTTP 1.1 new).
413–request Entity Too Large the size of the target document exceeds the size that the server is currently willing to handle. If the server thinks it can process the request later, it should provide a Retry-after header (HTTP 1.1 new).
414-request URI Too Long URI is too lengthy (HTTP 1.1 new).
415– not supported.MediaType.
The 416–requested range not satisfiable server does not meet the Range header specified by the customer in the request. (HTTP 1.1 new)
417– execution failed.
423– a locked error.

The 500-internal server Error server encountered unexpected conditions and was unable to complete the client's request.
500.12-The application is busy restarting on the WEB server.
The 500.13-web server is too busy.
500.15-Direct Request Global.asa is not allowed.
500.16–unc authorization credentials are incorrect. This error code is specific to IIS 6.0.
The 500.18–url authorization store cannot be opened. This error code is specific to IIS 6.0.
500.100-Internal ASP error.
The 501-not implemented server does not support the functionality required to implement the request, and the header value specifies the configuration that is not implemented. For example, a customer sends a put request that is not supported by the server.
When a gateway or proxy is 502-bad, the server returns an illegal response in order to complete the request to access the next server. It also says that the Web server received an invalid response when it was used as a gateway or proxy server.
The 502.1-cgi application timed out.
502.2-CGI Application error.
The 503-service unavailable service is unavailable and the server is unable to answer due to maintenance or overloading. For example, a servlet mightDataReturns 503 if the library connection pool is full. A retry-after header can be supplied when the server returns 503. This error code is specific to IIS 6.0.
When the 504-gateway Timeout network is timeout, it is used by the server acting as the proxy or gateway, indicating that the answer cannot be received from the remote server in a timely manner. (HTTP 1.1 new).
The HTTP version indicated in the request is not supported by the 505-HTTP version not supported server.

Native JS sends Ajax requests

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.