Cross-domain issues in js
The content of this article is about the cross-domain issues of js. Now I share it with you. Friends in need can refer to it.
The sample code is at E/AjaxGGW/For cross-domain issues, refer to the bookmark nuggets (correctly face cross-domain, don’t panic)
1. Cross-domain: The browser cannot execute scripts from other websites. It is caused by the browser's same origin policy. Security restrictions implemented by the server on JavaScript
2. The same-origin policy restricts the following behaviors:
Cookie, LocalStorage and IndexDB cannot be read
DOM and JS objects cannot be obtained
Ajax request cannot be sent
3. Common cross-domain scenarios
Same origin: domain name, protocol, and port are the same
http://www.nealyang.cn/index.html Call http://www.nealyang.cn/server.php Non-cross-domain
http://www.nealyang.cn/index.htmlCall http://www.neal.cn/server.php Cross-domain, different main domains
http://abc.nealyang.cn/index.html Call http://def.neal.cn/server.php Cross-domain , subdomain names are different
http://www.nealyang.cn:8080/index.html Call http:/ /www.nealyang.cn/server.php Cross-domain, different ports
https://www.nealyang. cn/index.html Call http://www.nealyang.cn/server.php Cross-domain, different protocols
4. Cross-domain solution
1)jsonpcross domain
In the html pageLoad static resource files from different domain names through the corresponding tags is allowed by the browser. Generally, we can dynamically create a script tag , and then request a URL with parameters to achieve cross-domain communication.
However, the biggest flaw is that only get request
$(function(){ /*jQuery支持jsonp的实现方式 */ $.ajax({ url:"www.baidu.com", type:"GET", dataType:"jsonp", //请求方式为:jsonp jsonpCallback:"callback", data:{ "username":"yaofan" } }) })
2)document.domain iframe cross-domain (1.html and document.domain iframe cross-domain.html)
The most important requirement is that the main domain name is the same, two html pages are required
<!-- 这种方式最主要的要求是主域名相同,假设目前a.nealyang.cn和b.nealyang.cn分别对应指定不同的ip服务器 a.nealyang.cn下有一个test.html文件 b.nealyang.cn下有一个1.html文件 --> <p>A页面</p> <!-- 利用iframe加载其他域下的文件 ,src中 --> <iframestyle = "display:none" name = "iframe1" id = "iframe" src = "http://b.nealyang.cn/1.html" frameborder = "0"> </iframe> <script type="text/javascript"> $(function(){ try{ document.domain = "nealyang.cn" //将document.domain设置为nealyang.cn,当iframe加载完毕后就可以获取nealyang.cn域下的全局对象 }catch(e){ $("#iframe").load(function(){ var jq = document.getElementById("iframe").contentWindow.$; jq.get("http://nealyang.cn/test.json",function(data){ console.log(data); }); }) } }) </script>
3)window.name iframe cross-domain (origin.html and target.html are not in Nuggets)
window.name attribute can set or return the name of the storage window of a string. Her magic is that the name value will still exist when loaded on different pages or different domains. It will not change without modification, and it can store very long names (2MB)
Assume that the index page requests data on the remote server. We create an iframe tag under the page. The src of the iframe points to the address of the server file (the iframe tag src can cross domain). The window is set in the server file. .name value, and then read the value of window.name in the iframe in index.html
If the index.html page and the page If the src of the iframe does not come from a different source, you cannot operate anything in the frame. The two pages are in different domains, and the source page cannot obtain the name value of the target page, because the name value is only visible to pages in the same domain.
4)Location.hash iframe cross domain
This cross The domain method is similar to the one introduced above. It also dynamically inserts an iframe and then sets its src as the server address. The server also outputs a js code and completes data transmission through communication with the child window.
And location.hash is actually the anchor point of the URL. For example, after opening the URL of http://www.nealyang.cn#Nealyang, enter it in the console location.hash will return the #Nealyang field.
[Note] In fact, location.hash and window.hash are similar. They are both methods that use global object properties. And these two methods are also the same as jsop. The same thing is that only get requests can be implemented
<script type="text/javascript"> function getData(url,fn){ var iframe = document.createElement("iframe"); iframe.style.display = "none"; iframe.src = url; iframe.onload = function(){ fn(iframe.contentWindow.location.hash.substring(1)); window.location.hash = ""; document.body.removeChild(iframe); }; document.body.removeChild(iframe); } //get data from server var url = "http://localhost:8080/data.php"; getData(url,function(data){ var jsondata = JSON.parse(data); console.log(jsondata.name + "" +jsondata.age); }); </script>
5)postMessage cross-domain (a.html and b.html )
#This is a cool API proposed by H5, including the postMessage method for sending information and the Message time for receiving information.
① 发送信息的postMessage方法是向外界窗口发送信息
otherWindow.postMessage(message,targetOrigin);
l otherWindow指的是目标窗口,是window.frames属性的成员或者是window.open方法创建的窗口。
l Message是要发送的消息,类型是String、Object
l targetOringin是限定消息接收范围,不限制用星号*
② 接受信息的message事件
var onmessage = function(event){ var data = event.data; var origin = event.origin; } if(typeof window.addEventListener != 'undefined'){ window.addEventListener('message',onmessage,false); }else if(typeof window.attachEvent != 'undefined'){ window.attachEvent('onmessage', onmessage); }
6) 跨域资源共享CORS
目前主流的跨域解决方案
1)简介
CORS是一个W3C标准,全称是“跨域资源共享”(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而客服了AJAX只能同源使用的限制。
CORS需要浏览器和服务器同时支持。
整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。
相关推荐:
The above is the detailed content of Cross-domain issues in js. 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

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

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

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What are the questions involved in the Yulong 8 Wine Master exam? What is the corresponding answer? How to pass the exam quickly? There are many questions that need to be answered in the Master of Wine Examination activities, and we can refer to the answers to solve them. These questions all involve knowledge of wine. If you need a reference, let’s take a look at the detailed analysis of the answers to the Yakuza 8 Wine Master exam questions! Detailed explanation of answers to questions in the Rulong 8 Wine Master exam 1. Questions about "wine". This is a distilled liquor produced by a distillery established by the royal family. It is brewed from the sugar of sugarcane grown in large quantities in Hawaii. What is the name of this wine? Answer: Rum 2. Question about "wine". The picture shows a drink made from dry ginseng and dry vermouth. It is characterized by the addition of olives and is known as "cockney"
