Discussion on cross-domain data interaction solution

Source: Internet
Author: User

First off the line, the first Ajax should be used to refer specifically to the use of XMLHttpRequest transmission of data technology, but just like the recent all the Web technology has been put into HTML5 name, now all the means of asynchronous access to data are called Ajax.

Cross-domain data interaction is a commonplace topic due to the existence of JavaScript homologous policies. There are many articles on the web, but with the passage of time and browser updates, part of the solution is no longer applicable, and there are some better ways. Throw away the pure server proxy This is not related to the front end of the scheme does not say, here is a brief summary of the other common ways.

JSONP

JSONP is the most common way of cross-domain data interaction, and the principle is that the script tag of HTML can load and execute other domain JS files. Site B passes the data to be provided as a parameter to a global function defined by site A, and site A refers to this file to obtain data across domains, and a station can also put a small number of parameters in the script tag SRC to submit to station B. Outside the chain JS this scheme only supports get, under IE URL length can not exceed 2,083 bytes limit and for security reasons, generally not used to submit data.

Someone through the backend proxy makes it possible to get any page content in this way, and also adds support for post, such as:

HTML<ScriptType="Text/javascript"Src="Http://www.ajax-cross-domain.com/cgi-bin/ACD/ACD.js?uri= (http://www.google.com)" ></Script><ScriptType="Text/javascript" >Alert(Acd.responsetext);</script>< script type= "Text/javascript" Span class= "Hljs-attribute" >src= "Http://www.ajax-cross-domain.com/cgi-bin/ACD/ACD.js?" Uri= (http://216.92.131.147/dotserv/ACD/runit/post.cgi) &method=post&postdata= (name=fred&[email  protected]) "></script>< Span class= "Hljs-tag" ><script type=  "Text/javascript" > Alert (acd.responsetext) ; </SCRIPT>           

In fact, the solution is to use the backend to output any page as a JS variable, the backend based on the relevant identity in the URL to determine the request method and parameters, and does not solve the big data submission problem.

Native Form +redirect+callback

The native form form supports submitting data to other domains, we just need to point the target of the form to the hidden iframe on the page, then we can implement the non-flush commit, and the remaining question is how to get the result after submission. For example, site a form submits data to site B, usually we will process the request at Site B, redirect to a proxy page under Site A, and the URL with the parameters to identify processing results. Next, a station under the proxy page can parse the URL parameters, passed to the parent page callback function to deal with.

Flash

With Flash's urlloader, cross-domain data interactions can also be easily implemented. As long as site B's cross-Domain policy file (crossdomain.xml) contains the site A,a station, you can get data for station B and submit the data to station B. We can put JS and flash interactive encapsulation, more convenient to use. Here is a version of someone else's package, which is almost identical to the native XMLHttpRequest:

JSvar req;functioncallback () {if (req.readyState = = Span class= "Hljs-number" >4) {try {if (req.status! = 200) {alert (else {alert (catch (e) {alert (function test_get () {req = new crossxhr (); req.onreadystatechange = callback; Req.open ( ' GET ',  ' http://www.pliantdev.com/support/test.xml '); Req.send ();}                
Iframe+xmlhttprequest

If site B has a proxy page, with native Ajax (XMLHttpRequest) to the other pages of B station for various data interaction, then we in a station with IFrame introduced this proxy page, only need to solve the IFRAME cross-domain problem can be. In fact, if A and B belong to the same large domain, setting the document.domain on both sides is OK for the root domain, and if it is a completely different two domain, there are many ready-made solutions, such as the classic window.name. Even better, almost all modern browsers, except IE6 and IE7, support data communication with Window.postmessage for different iframe. PMXDR is a library that uses PostMessage to pass data to a hidden out-of-site IFRAME to enable cross-domain AJAX,LIBXDR to be further encapsulated for better use:

Jsvar req = new XDR();req.open("POST", "http://code.eligrey.com/pmxdr/libxdr/demo.php");req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");req.onload = function() { alert(this.responseText); // alerts "foo is bar"};request.send("foo=bar");

It is worth noting that this scenario only needs to deploy a proxy page at site B, and any other site can interact with it through this page, it is not too secure, this point pmxdr take into account, In Pmxdr-host.js, there is a variable alwaystrustedorigins, which is an array that supports the use of regular definitions to allow interactive sites.

The ultimate solution: CORS

In fact, in addition to IE6, IE7, most modern browsers have supported cross-domain resource sharing (cross-origin Resource sharing, or CORS) standards, which is the ultimate solution for cross-domain Ajax. With this standard, you can easily cross the domain by adding one to the response header:

Access-Control-Allow-Origin: http://hello-world.example

This header defines which domains are allowed to interact with themselves, and if defined as * means that any domain is allowed, this is certainly not recommended. In a standard browser other than IE, this makes it possible to cross-domain Ajax. For IE, you need to change the new Xdomainrequest object to send the request, others are similar. In addition, there are several headers that can be used to set the allowable submission method and so on, if you want to support authentication or submit data in the format of XML to the server, you need a pre-request, here are more instructions.

Summarize

Different scenarios have their own different usage scenarios, who are good and who are bad can not generalize. General, cross-domain access to data personal habits with JSONP, cross-domain submission of data personal habits with form +callback. With the popularity of modern browsers, native XHR can also try, flash can be used as a substitute for demotion. Finally, if you want to choose a library that encapsulates a variety of cross-domain implementations, consider the IO components of the Yui3.

This article mentions some of the component links:

    • AJAX Cross Domain (convert any page to JS variable on the server)
    • Cross Domain XHR (based on Flash, interface and XHR are highly consistent)
    • PMXDR (cross-domain scenario using postmessage and IFRAME)
    • LIBXDR (Pmxdr's re-encapsulation, interface simulates IE's xdomainrequest)
    • YUI3 IO components (cross-domain scenarios based on flash or native XHR)

Discussion on cross-domain data interaction solution

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.