Sharing examples of using js to solve cross-domain problems
What is cross-domain? As long as the protocol, domain name, or port are any different, they are regarded as different domains.
URL 说明 是否允许通信 http://www.a.com/a.jshttp://www.a.com/b.js 同一域名下 允许http://www.a.com/lab/a.jshttp://www.a.com/script/b.js 同一域名下不同文件夹 允许http://www.a.com:8000/a.jshttp://www.a.com/b.js 同一域名,不同端口 不允许http://www.a.com/a.jshttps://www.a.com/b.js 同一域名,不同协议 不允许http://www.a.com/a.jshttp://70.32.92.74/b.js 域名和域名对应ip 不允许http://www.a.com/a.jshttp://script.a.com/b.js 主域相同,子域不同 不允许http://www.a.com/a.jshttp://a.com/b.js 同一域名,不同二级域名(同上) 不允许(cookie这种情况下也不允许访问)http://www.cnblogs.com/a.jshttp://www.a.com/b.js 不同域名 不允许
Differences in ports and protocols can only be solved through the background.
Cross-Origin Resource Sharing (CORS)
CORS (Cross-Origin Resource Sharing) cross-domain resource sharing defines how the browser and server should communicate when accessing cross-domain resources. The basic idea behind CORS is to use custom HTTP headers to allow the browser to communicate with the server to determine whether the request or response should succeed or fail.
<script type="text/javascript"> var xhr = new XMLHttpRequest(); xhr.open("GET", "/trigkit4",true); xhr.send();</script>
The above trigkit4 is a relative path. If we want to use CORS, the relevant Ajax code may be as follows:
<script type="text/javascript"> var xhr = new XMLHttpRequest(); xhr.open("GET", "http://segmentfault.com/u/trigkit4/",true); xhr.send();</script>
The difference between the code and the previous one is that the relative path is replaced by another domain. The absolute path is the interface address you want to access across domains.
The server side supports CORS mainly by setting Access-Control-Allow-Origin. If the browser detects the corresponding settings, it can allow Ajax cross-domain access.
To solve the cross-domain problem, we can use the following methods:
Cross-domain through jsonp
Now the question comes? What is jsonp? Wikipedia's definition is: JSONP (JSON with Padding) is a "usage mode" of the data format JSON, which allows web pages to request data from other domains.
JSONP, also called padded JSON, is a new method of applying JSON, which is just JSON included in function calls, for example:
callback({"name","trigkit4"});
JSONP consists of two parts: callback functions and data. The callback function is the function that should be called in the page when the response comes, and the data is the JSON data passed into the callback function.
In js, it is not possible to directly use XMLHttpRequest to request data on different domains. However, it is possible to introduce js script files from different domains on the page. jsonp uses this feature to achieve it. For example:
<script type="text/javascript"> function dosomething(jsondata){ //处理获得的json数据 }</script><script src="http://example.com/data.php?callback=dosomething"></script>
After the js file is successfully loaded, the function we specified in the url parameter will be executed, and the json data we need will be passed in as a parameter. Therefore, jsonp requires corresponding cooperation from the server-side page.
<?php $callback = $_GET['callback'];//得到回调函数名$data = array('a','b','c');//要返回的数据echo $callback.'('.json_encode($data).')';//输出?>
Finally, the output result is: dosomething(['a','b','c']);
If your page uses jquery, then the method encapsulated by it is It is very convenient to perform jsonp operations.
<script type="text/javascript"> $.getJSON('http://example.com/data.php?callback=?,function(jsondata)'){ //处理获得的json数据 });</script>
jquery will automatically generate a global function to replace the question mark in callback=?, and then automatically destroy it after obtaining the data. In fact, it acts as a temporary proxy function. The $.getJSON method will automatically determine whether it is cross-domain. If it is not cross-domain, it will call the ordinary ajax method; if it is cross-domain, it will call the jsonp callback function in the form of asynchronously loading the js file.
Advantages and Disadvantages of JSONP
The advantages of JSONP are: it is not restricted by the same-origin policy like the Ajax request implemented by the XMLHttpRequest object; it has better compatibility and can be used in older browsers. It can run in any server and does not require XMLHttpRequest or ActiveX support; and after the request is completed, the result can be returned by calling callback.
The disadvantages of JSONP are: it only supports GET requests and does not support other types of HTTP requests such as POST; it only supports cross-domain HTTP requests and cannot solve the problem between two pages in different domains. Issues making JavaScript calls.
Comparison between CORS and JSONP
Compared with JSONP, CORS is undoubtedly more advanced, convenient and reliable.
1、 JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。 2、 使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理。 3、 JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS)。
Cross subdomains by modifying document.domain
Browsers all have a same-origin policy. One of its limitations is that in the first method, we said that it cannot be done through ajax. Request documents from different sources. Its second limitation is that js cannot interact between frames in different domains in the browser.
Different frameworks can obtain window objects, but they cannot obtain the corresponding properties and methods. For example, there is a page whose address is http://www.example.com/a.html. There is an iframe in this page and its src is http://example.com/b.html. Obviously , this page and the iframe frame inside it are in different domains, so we cannot get the things in the iframe by writing js code in the page:
<script type="text/javascript"> function test(){ var iframe = document.getElementById('ifame'); var win = document.contentWindow;//可以获取到iframe里的window对象,但该window对象的属性和方法几乎是不可用的 var doc = win.document;//这里获取不到iframe里的document对象 var name = win.name;//这里同样获取不到window对象的name属性 }</script><iframe id = "iframe" src="http://example.com/b.html" onload = "test()"></iframe>
At this time, document.domain can be used To use it, we only need to set the document.domain of the two pages http://www.example.com/a.html and http://example.com/b.html to the same domain name. But it should be noted that the setting of document.domain is limited. We can only set document.domain to itself or a higher-level parent domain, and the main domain must be the same.
1.在页面 http://www.example.com/a.html 中设置document.domain:
<iframe id = "iframe" src="http://example.com/b.html" onload = "test()"></iframe><script type="text/javascript"> document.domain = 'example.com';//设置成主域 function test(){ alert(document.getElementById('iframe').contentWindow);//contentWindow 可取得子窗口的 window 对象 }</script>
2.在页面 http://example.com/b.html 中也设置document.domain:
<script type="text/javascript"> document.domain = 'example.com';//在iframe载入这个页面也设置document.domain,使之与主页面的document.domain相同</script>
修改document.domain的方法只适用于不同子域的框架间的交互。
使用window.name来进行跨域
window对象有个name属性,该属性有个特征:即在一个窗口(window)的生命周期内,窗口载入的所有的页面都是共享一个window.name的,每个页面对window.name都有读写的权限,window.name是持久存在一个窗口载入过的所有页面中的
使用HTML5的window.postMessage方法跨域
window.postMessage(message,targetOrigin) 方法是html5新引进的特性,可以使用它来向其它的window对象发送消息,无论这个window对象是属于同源或不同源,目前IE8+、FireFox、Chrome、Opera等浏览器都已经支持window.postMessage方法。
相关推荐:
The above is the detailed content of Sharing examples of using js to solve cross-domain problems. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools