Detailed description of ajax cross-Origin data submission instances

Source: Internet
Author: User

Currently, the implementation of ajax methods includes the native javascript method and the current jquery $. ajax method. Next we will introduce the cross-Origin data submission using their instances. I hope this method will be helpful to you.

For security reasons, in AJAX applications, browsers usually restrict cross-Origin data submission, but this is a very common requirement. For example, if you submit some request data to the B .com server on the.com page, the B .com server returns the response content to the.com page after processing the request. How can we solve this problem? Using js is a simple and easy-to-implement solution. The disadvantage is that the Code is related to the application and the template mechanism cannot be abstracted for reuse.

Specifically, a.html dynamically adds a javascript-type node to the javascript event of data submission. This node points to the dynamic page of B .com that receives data. For example, php is called B. php.
But in the browser (including the IE and Mozilla systems and Opera systems), it seems like it contains a real js script, so it will request this
B. php: After processing the corresponding logic in B. php, return the javascript code that prints the result in a short segment. After returning to a.html, the browser is responsible for parsing this small javascript code and printing or displaying the request results. It is through this 'spoofing 'browser that implements the data cross-origin function.

Principles of ajax

XMLHttpRequest is the core mechanism of ajax. It is first introduced in ie5. it is a technology that supports asynchronous requests. Simply put, javascript can promptly request and process responses to the server without blocking users. Achieve the effect of refreshing.
So let's start with XMLHttpRequest to see how it works.
First, let's take a look at the attributes of the XMLHttpRequest object.
Its attributes include:
Onreadystatechange the event handler of the event triggered by each state change.
The string format of responseText returned data from the server process.
ResponseXML is a DOM-compatible document data object returned by the server process.
Status Code returned from the server, such as common 404 (not found) and 200 (ready)
String information of the status Text accompanied by the status code
ReadyState object status value, 0-not initialized 1-loading 2-Loading completed 3-interaction 4-finished.

However, because of the differences between browsers, creating an XMLHttpRequest object may require different methods. This difference is mainly reflected in IE and other browsers.
The following lists the XMLHttpRequest objects created in different browsers.

The Code is as follows: Copy code
Var xmlHttp = false;
// Create an XMLHttpRequest object for IE
Try {
// Use a version of Msxml to create
XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
// Use another object to create
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e2 ){

}
}

If (! XmlHttp & typeof XMLHttpRequest! = 'Undefined '){
// Create an XMLHttpRequest object for other non-Microsoft browsers
XmlHttp = new XMLHttpRequest ();
}

This process is divided into three steps. First, we define an xmlHttp to reference the created XMLHttpRequest.
Then, we try to create this object in Microsoft's browser and use the Msxml. XMLHTTP object to create it,
If it fails, try macrosoft. XMLHTTP to create it. Finally, we will create this object for non-Microsoft browsers.
In this way, we have created an XMLHttpRequest object. Let's see how to send an XMLHttpRequest request.

The Code is as follows: Copy code
Function executeXMLHttpRequest (callback, url)
{
// Handle non-Microsoft browsers
If (window. XMLHttpRequest)
{
Xhr = new XMLHttpRequest ();
Xhr. onreadystatechange = callback;
Xhr. open ("Get", url, true );
Xhr. send (null );
}
// Process the situation of the micro-soft Browser
Else if (window. ActiveXObject)
{
Xhr = new ActiveXObject ("macrosoft. XMLHttp ");
If (xhr)
{
Xhr. onreadystatechage = callback;
Xhr. open ("Get", url, true );
Xhr. send ();
}
}
}


As shown above, the execution of XMLHttpRequest is actually used to process the differences between browsers,
It still needs to be processed for different browsers, but it looks very intuitive.
In the above Code, the most important thing is: xhr. onreadystatechage = callback
It defines the callback function, which is automatically executed once it is responded.
Xhr. open ("" Get ", url, true); true indicates that you want to execute the request asynchronously.
For callback, we have:

The Code is as follows: Copy code
Function processAjaxResponse (){
// The status is marked as completed
If (xhr. readyState = 4 ){
// Ready
If (xhr. status = 200 ){
Document. getElementById ('votes '). innerHTML = xhr. responseText;
} Else {
Alert ("There was a problem retrieving the XML data:" + xhr. statusText );
}
}
}

That is to say, once the server finishes processing XMLHttpRequest and returns it to the browser,
The callback method assigned by xhr. onreadystatechange is automatically called.
The above is the entire workflow of XMLHttpRequest,
It first checks the overall status of XMLHttpRequest and ensures that it has been completed (readyStatus = 4 ),
Then, query the Request status based on the server settings,
If everything is ready (status = 200), perform the following operations.
The process steps are not complex. There are three steps:
1. Create an XMLHttpRequest object
2. Send an XMLHttpRequest request
3. Output The results returned by the server after the request to html
Next we will focus on how to implement ajax cross-Origin data submission!
Use jquery's $. ajax method.

The Code is as follows: Copy code
$ (Document). ready (function (){
$ ("Input [name = username]"). blur (function (){
$. Ajax ({
Type: "GET", // The get method is required !!!
Url: "http://xxx.com/test.php ",
DataType: "jsonp", // It must be specified as jsonp
Jsonp: "json_callback", // you must specify the name of the callback function to be received by the server! See how test. php receives
Data: {username :$ ('# username'). val ()},
Success: function (json ){
If (json. msg = 'err ')
Alert (json.info );
Else if (json. msg = 'OK ')
Alert ('submitted successfully ');
Else
Alert ('submission failed ');
},
Error: function (){
Alert ("error !!! ");
},

});

});

});


Test. php

The Code is as follows: Copy code


// Receives the callback function name from js,
// In order to assemble the following echo... $ username = $ _ GET ['username'];
$ Jsonp_callback = $ _ GET ['json _ callback'];
Echo $ jsonp_callback, '({"msg": "err", "info": "'. $ username. '"})'; exit;

At this point, the cross-Origin data acquisition and data submission are complete!

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.