Ajax cross-Domain submit data instance detailed

Source: Internet
Author: User

For security reasons, browsers typically restrict cross-domain submission of data in AJAX applications, but this is precisely the most common requirement. For example, on a a.com page to submit some request data to the B.Com server, B.Com Server processing request after the completion of the response to return the content to the A.com page. How to solve it, the use of JS is relatively simple and easy to implement the scheme, the disadvantage is that the code and application-related, can not abstract the template mechanism for reuse.

The specific principle and implementation is this, on the A.com page, assume that called a.html, to submit data in the JavaScript event dynamically add a type of JavaScript node, This node points to the dynamic page of the B.Com that receives the data, in PHP, for example, assuming that the b.php page is called.
But in browsers (IE and Mozilla, and opera) it seems like it contains a real JS script, so it's going to ask for this
b.php, after processing the corresponding logic in b.php, it returns a small piece of JavaScript code that prints the result. After returning to a.html, the browser is responsible for parsing this little piece of JavaScript code, printing or displaying the result of the request. It is through this ' deception ' browser that the data Cross-domain function is achieved.

The principle of Ajax

XMLHttpRequest is the core mechanism of Ajax, which is introduced first in IE5 and is a technology that supports asynchronous requests. Simply put, JavaScript is the time to request and process responses to the server without blocking the user. No refreshing effect is achieved.
So let's start with XMLHttpRequest and see how it works.
First, let's look at the properties of the XMLHttpRequest object.
Its properties are:
onReadyStateChange the event handler for the event that triggers each state change.
ResponseText A string form that returns data from a server process.
Responsexml a DOM-compliant document data object returned from a server process.
Status number code returned from the server, such as common 404 (not Found) and 200 (ready)
Status Text string information accompanying the status code
ReadyState object state Value, 0-Uninitialized 1-Loading 2-loading complete 3-Interactive 4-complete.

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

  code is as follows copy code
var = false;
//Create XMLHttpRequest object for IE
try {
   //Use one version of MSXML to create
    xmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
} catch (e) {
    try {
       ///Use another object of it to create
&nbs p;       xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
   } catch (E2) {
 
   }
}
 
if (!xmlhttp &&am P typeof XMLHttpRequest!= ' undefined ') {
   //Create XMLHttpRequest object for other non-Microsoft browsers
    XmlHttp = new XMLHttpRequest ();
}

This process is divided into three steps, first we define a XMLHTTP to reference the created XMLHttpRequest.
We then try to create the object in Microsoft's browser, first with the Msxml.xmlhttp object,
If you fail, try using Macrosoft again. XMLHTTP to create it. Finally, we create this object for non-Microsoft browsers.
So, we've created a XMLHttpRequest object, so let's look at how to make a XMLHttpRequest request.

The code is as follows Copy Code
function Executexmlhttprequest (Callback,url)
{
Handling non-Microsoft browsers
if (window. XMLHttpRequest)
{
Xhr=new XMLHttpRequest ();
Xhr.onreadystatechange = callback;
Xhr.open ("Get", url,true);
Xhr.send (NULL);
}
Dealing with Microsoft browsers
else if (window. ActiveXObject)
{
Xhr=new ActiveXObject ("Macrosoft"). XMLHttp ");
if (XHR)
{
Xhr.onreadystatechage=callback;
Xhr.open ("Get", url,true);
Xhr.send ();
}
}
}


Visible from above, execution XMLHttpRequest actually most of the code is still used to handle the differences between browsers,
It still has to be handled differently for different browsers, but it also looks very intuitive.
In the above code, the key is: Xhr.onreadystatechage=callback
It defines a callback function that is automatically executed once it is responded to.
Xhr.open ("" Get ", url,true); True indicates that you want to execute the request asynchronously.
For callback, we have:

  code is as follows copy code
function () {
   /status identified as completed
Processajaxresponse nbsp;  if (xhr.readystate = 4) {
       //Ready
   & nbsp;    if (xhr.status = =) {
             document.getElementById (' votes '). InnerHTML = Xhr.responsetext;
       } else {
             alert ("There was a problem retrieving the XML data:" +xhr.statustext);
       }
   }
}

That is, once the server finishes processing XMLHttpRequest and returns to the browser,
The callback method assigned with Xhr.onreadystatechange will be invoked automatically.
It's almost the entire workflow of XMLHttpRequest,
It examines the overall state of the XMLHttpRequest first and ensures that it is already finished (readystatus=4),
The request status is then queried based on the server's settings.
If everything is ready (status=200), then do what you need to do below.
The process steps are not complex on three steps:
1. Create a XMLHttpRequest Object
2. Send a XMLHttpRequest request
3. Output The result data returned by the server to the HTML after the request
Here's what to do if you want to implement AJAX Cross-domain submission data!
Just use the $.ajax method of jquery.

The code is as follows Copy Code
$ (document). Ready (function () {
$ ("input[name=username]"). blur (function () {
$.ajax ({
Type: ' Get ',//MUST be get way!!!
URL: "http://xxx.com/test.php",
DataType: "Jsonp",//must be specified is JSONP
JSONP: "Json_callback",//must specify the name of the callback function to be received by the server side! Please 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 (' submit successfully ');
Else
Alert (' Submit failed ');
},
Error:function () {
Alert ("Error!!!");
},

});

});

});


test.php

The code is as follows Copy Code


Receive the callback function name that JS passes over,
In order to assemble in echo below ... $username = $_get[' username '];
$jsonp _callback = $_get[' Json_callback '];
echo $jsonp _callback, ' ({"MSG": "Err", "info": "'. $username. '"}) '; Exit

Here, cross-domain access to data, the submission of data officially completed!

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.