Ajax implementation asynchronous Request step __ajax

Source: Internet
Author: User
Tags browser cache

First, the native JS implementation:

var request = new XMLHttpRequest (); Create a XMLHttpRequest () object

Initiates an HTTP request, but does not send the request to the server, and the last parameter defaults to False, which is sent asynchronously.
Request.open ("get/post", url, true/false); Pass parameters directly on the URL when you use the Get method.


The Post method is used to pass parameters to the server via the Send method
var data = "Str"; STR Gets the value of a form element or other content that needs to be updated


Sets the header information to indicate that the form element is being sent
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

Send request to service side
Request.send (Null/data);


The onreadystatechange event triggers when the ReadyState property changes, monitoring the ReadyState property
Request.onreadystatechange = function () {

A status code of 4 indicates that the request is complete and the response content is ready
if (request.readystate = = 4) {


Status Code 304 indicates that the request resource has not been modified and can use the browser cache
if ((Request.status >= && request.status <) | | request.status = = 304) {


The server returns a JSON object, formatted as a JS object using the Json.parse () method.
var data = Json.parse (Request.responsetext);


if (data.success) {
Process the data returned successfully by the response

    
} else {
Processing data returned by response failure


}
} else {
Processing the data returned by the request failure
}
}
}

Back-end interaction conventions that return different information when the contract is success true or false.
The Success property makes it easy for front-end calls to return information.
{
"Success": true,
"MSG": "XXX",
}

Ii. Cross-Domain Solutions

Suppose our page or application is already on the http://www.test1.com, and we intend to extract the data from the http://www.test2.com request. In general, if we use AJAX directly to request will fail, the browser will also return the "Source mismatch" error, "Cross-domain" is the origin. Cors is the abbreviation for Cross source resource sharing (Cross-origin Resource sharing). It is the standard of the consortium and is the fundamental solution to the cross source Ajax request. Cors allows any type of request compared to JSONP can only send a GET request.
Using cors,http://www.test2.com just add a header, you can allow requests from http://www.test1.com, the following figure is my hander () settings in PHP, "*" Indicates that any domain is allowed to submit a request to our server: You can also set the specified domain name, such as the domain name http://www.test2.com, then allow requests from this domain name: the header I have set is "*", and any request comes over the server we can handle & Response, you can see the header information setting in the Debugging tool, where a message in the red box is "access-control-allow-origin:*", indicating that we have enabled cors, as shown below. The normal use of Ajax will require the normal consideration of cross-domain problems, so the great program workers have to toss out a series of cross-domain problem solutions, such as JSONP, cors and so on.

Cors and JSONP Use the same purpose, but more powerful than JSONP. JSONP only supports GET requests, Cors supports all types of HTTP requests. The advantage of JSONP is that it supports older browsers and can request data from Web sites that do not support cors.
The basic principle of JSONP is that the HTML <script> tag can get the characteristics of any source JavaScript code and achieve Cross-domain access to the data. To define a callback locally, get the data from the remote API (pass the callback function name) through the SRC attribute of the <script> tag, and the remote server API needs to conform to the JSONP specification, A function call code that rewrites the output data in the original JSON format to JavaScript (callback is a function, the original JSON data is a parameter), so the API returns no longer JSON-formatted data but JavaScript code.

Script type= "Text/javascript" src= "Http://www.youxiaju.com/js/jquery-1.4.2.min.js" ></script>  
< Script type= "Text/javascript" >  
$ (function () {  
$.ajax (  
    {  
        type: ' Get ',  
        URL: ' http:// www.youxiaju.com/validate.php?loginuser=lee&loginpass=123456 ',  
        dataType: ' Jsonp ',  
        jsonp: " Jsoncallback ",  
        success  : function (data) {  
            alert (" User name: "+ data.user +" Password: "+ data.pass);  
        },  
        Error:function () {  
            alert (' fail ');  
        }  
}) </script>  
Cross-domain resource sharing CORS detailed

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.