


What is cross-domain? Introduction to four ways of cross-domain JavaScript
This article brings you a detailed explanation of PHP synergy implementation (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. What is cross-domain
When any of the protocol, subdomain name, main domain name, and port number are different, they are all counted as different domains. Requesting resources from different domains is considered "cross-domain".
For example: http://www.abc.com/index.html requests http://www.efg.com/service.php.
Cross-domain does not mean that the request cannot be sent out, the request can be sent out, the server can receive the request and return the result normally, but the result is intercepted by the browser . The reason why it occurs across domains is that it is restricted by the same-origin policy. The same-origin policy requires that the source is the same for normal communication, that is, the protocol, domain name, and port number are all exactly the same.
You can refer to the picture below to help you understand cross-domain in depth.2. What is the same-origin policy and its restrictions
The same-origin policy restricts how documents or scripts loaded from one source interact with resources from another source. . This is a critical security mechanism for isolating potentially malicious files. Its existence can protect user privacy information, prevent identity forgery, etc. (read Cookie). The content restricted by the same origin policy includes:- Cookie, LocalStorage, IndexedDB and other storage content
- DOM node
- AJAX request cannot be sent
But there are three tags that allow cross-domain loading of resources:
1.<img src="/static/imghw/default1.png" data-src="http://crossdomain.com/jsonServerResponse?jsonp=fn" class="lazy" alt="What is cross-domain? Introduction to four ways of cross-domain JavaScript" > 2.<link> 3.<script></script>
3. Cross-domain processing method 1 - JSONP
1.JSONP principleUtilization<script># With this open policy of the ## element, web pages can obtain JSON data dynamically generated from other sources. JSONP requests must be supported by the other party's server. <code></script>2. Comparison between JSONP and AJAX
JSONP and AJAX are the same. They are both ways in which the client sends a request to the server and obtains data from the server. But AJAX belongs to the same-origin policy, and JSONP belongs to the non-original policy (cross-domain request)
3. JSONP advantages and disadvantages
The advantage of JSONP is that it has good compatibility and can be used to solve cross-origin problems of mainstream browsers. Domain data access issues.
The disadvantage is that only supporting the get method has limitations.4.JSONP process (take the third-party API address as an example, there is no need to consider the background program)
- Declare a callback function, its function name (such as fn) is used as a parameter value to be passed to the server that requests cross-domain data. The function parameter is to obtain the target data (data returned by the server).
- Create a
- <script><p> tag, assign the cross-domain API data interface address to the src of the script, and also request the server in this address Pass the function name (parameters can be passed via question marks:?callback=fn). <code></script>
-
<script> function fn(data) { alert(data.msg); } </script> <script></script>
Copy after loginwhere fn is the callback function registered by the client. The purpose is to obtain the json data on the cross-domain server and process the data.
- After the server receives the request, it needs to perform special processing: concatenate the passed in function name and the data it needs to give you into a string, for example: passed in The function name is fn, and the data it prepares is fn([{"name":"jianshu"}]).
fn({ msg:'this is json data'})
5.jQuery’s jsonp formatJSONP is a GET and asynchronous request, and there are no other requests. method and synchronous request, and jQuery will clear the cache for JSONP requests by default.
$.ajax({
url:"http://crossdomain.com/jsonServerResponse",
dataType:"jsonp",
type:"get",//可以省略
jsonpCallback:"fn",//->自定义传递给服务器的函数名,而不是使用jQuery自动生成的,可省略
jsonp:"jsonp",//->把传递函数名的那个形参callback变为jsonp,可省略
success:function (data){
console.log(data);}
});
整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。 CORS要求浏览器(>IE10)和服务器的同时支持,是跨域的根本解决方法,由浏览器自动完成。 例如:网站http://localhost:63342/ 页面要请求http://localhost:3000/users/userlist 页面,userlist页面返回json字符串格{name: 'Mr.Cao', gender: 'male', career: 'IT Education'} 在响应头上添加Access-Control-Allow-Origin属性,指定同源策略的地址。同源策略默认地址是网页的本身。只要浏览器检测到响应头带上了CORS,并且允许的源包括了本网站,那么就不会拦截请求响应。 五、处理跨域方法三——WebSocket Websocket是HTML5的一个持久化的协议,它实现了浏览器与服务器的全双工通信,同时也是跨域的一种解决方案。WebSocket和HTTP都是应用层协议,都基于 TCP 协议。但是 WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。 原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。 六、处理跨域方法四——postMessage 如果两个网页不同源,就无法拿到对方的DOM。典型的例子是iframe窗口和window.open方法打开的窗口,它们与父窗口无法通信。HTML5为了解决这个问题,引入了一个全新的API:跨文档通信 API(Cross-document messaging)。这个API为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。postMessage方法的第一个参数是具体的信息内容,第二个参数是接收消息的窗口的源(origin),即"协议 + 域名 + 端口"。也可以设为*,表示不限制域名,向所有窗口发送。 接下来我们看个例子:1.CORS原理
2.CORS优缺点
优点在于功能更加强大支持各种HTTP Method,缺点是兼容性不如JSONP。
只需要在服务器端做一些小小的改造即可:header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:POST,GET");
//在服务器端设置同源策略地址
router.get("/userlist", function (req, res, next) {
var user = {name: 'Mr.Cao', gender: 'male', career: 'IT Education'};
res.writeHeader(200,{"Access-Control-Allow-Origin":'http://localhost:63342'});
res.write(JSON.stringify(user));
res.end();
});
//前端代码:
<p>user input:<input></p>
<script></script>
<script>
var socket = io('http://www.domain2.com:8080');
// 连接成功处理
socket.on('connect', function() {
// 监听服务端消息
socket.on('message', function(msg) {
console.log('data from server: ---> ' + msg);
});
// 监听服务端关闭
socket.on('disconnect', function() {
console.log('Server socket has closed.');
});
});
document.getElementsByTagName('input')[0].onblur = function() {
socket.send(this.value);
};
</script>
//Nodejs socket后台:
var http = require('http');
var socket = require('socket.io');
// 启http服务
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
// 监听socket连接
socket.listen(server).on('connection', function(client) {
// 接收信息
client.on('message', function(msg) {
client.send('hello:' + msg);
console.log('data from client: ---> ' + msg);
});
// 断开处理
client.on('disconnect', function() {
console.log('Client socket has closed.');
});
});
http://localhost:63342/index.html页面向http://localhost:3000/message.html传递“跨域请求信息”//发送信息页面 http://localhost:63342/index.html
<meta>
<title>跨域请求</title>
<iframe></iframe>
<input>
<script>
function run(){
var frm=document.getElementById("frm");
frm.contentWindow.postMessage("跨域请求信息","http://localhost:3000");
}
</script>
//接收信息页面 http://localhost:3000/message.html
window.addEventListener("message",function(e){ //通过监听message事件,可以监听对方发送的消息。
console.log(e.data);
},false);
The above is the detailed content of What is cross-domain? Introduction to four ways of cross-domain JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

HTML5 Interview Questions 1. What are HTML5 multimedia elements 2. What is canvas element 3. What is geolocation API 4. What are Web Workers

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4
