We know that ajax actually uses XMLHttpRequest objects to perform asynchronous data interaction. For security reasons, the browser does not allow cross-origin operations of js code, so js cross-origin operations will be rejected.
Specific situations include:
1. Mutual access between the local domain and subdomain: http://www.aa.com/and book.aa.com
2. Mutual access between the domain and other domains: http://www.aa.com/and http://www.bb.com/ iframe
3. Mutual access between the domain and other domains: http://www.aa.com/and http://www.bb.com/ use XMLHttpRequest to access the proxy
4. Mutual access between the current domain and other domains: http://www.aa.com/and http://www.bb.com/ create dynamic scripts with JS
Today we will mainly discuss the solution in section 4th. the difference between this and the above is that the request uses the <script> tag for the request. This requirement is also required by you to develop both domains. The principle is JS file injection. a JS tag is generated within a in the domain. Its SRC points to a page B in another domain of the request and B returns data, you can directly return the JS Code. Because the src attribute of the script can be cross-origin.
Here we need to use the JQuery. getScript (url, callback) method. The url is the URL strength of the script file. The callback function calls the callback function after the script resource has been loaded and evaluated.
First create a js file in bb.com, test. js
1 var ojb = {msg: 'js cross-origin request succeeded '};
Then load the test. js script with $. getScript on the aa.com page.
1 $ (function (){
2 $. getScript ('HTTP: // www.bb.com/test.js', function (){
3 if (ojb ){
4 alert (obj. msg );
5}
6 });
7 });
The biggest benefit of using the $. getScript function is to ensure that the callback function is called after the script is loaded.
I personally think this method is easier than using proxy and iframe.
Source: http://hyl8218.cnblogs.com