The examples in this article describe the method of cross-domain implementation in js. Share it with everyone for your reference. The specific analysis is as follows:
Due to the restrictions of the same-origin policy, XMLHttpRequest is only allowed to request resources from the current source (including domain name, protocol, and port).
The difference between json and jsonp:
JSON is a data exchange format, while JSONP is an unofficial cross-domain data exchange protocol created by developers.
Thescript tag is often used to load resources from different domains and can bypass the same-origin policy. (Anyone with the src attribute can obtain foreign files).
If the requested remote data itself is an executable js, then these js will be executed (equivalent to eval).
Method 1:
Use script tag to request ()
Before using the script tag to request, first declare the callback function,
1 2 3 4 |
|
Using JSON to transfer javascript objects is the simplest way. This cross-domain communication method is called JSONP.
Remote server patchwork string:
Callback function name ({"name1":"data1","name2","data2"})
This kind of json data is pieced together in the background and returned to the client in the form of passing parameters through the callback function
(You can call it directly, which is equivalent to eval processing the obtained string)
For example:
1 2 |
|
Method 2:
It is simpler to implement the foreign loading method with jquery (the same as the asynchronous request method of ajax)
1 2 3 4 5 |
|
or abbreviated form
1 2 3 4 |
|
Method 3:
Ajax cross-domain server proxy
Set up a proxy program (proxy.jsp...) in the background of the same source;
Interact with servers in foreign domains on the server side.
jquery frontend data transmission:
For example:
1 2 3 4 5 6 7 8 9 10 |
|
Background data processing:
1 2 3 4 5 6 |
|
Method 4:
Use the src attribute of the iframe tag to perform cross-domain access, store the obtained value in the current iframe, and then obtain the value in the body of the iframe on the same page.
1 2 3 4 5 6 7 8 9 10 |
|
Method 5:
Websocket in HTML5 can provide cross-domain access;
Create a websocket object:
The main event types processed are (onopen, onclose, onmessage, onerror);
For example:
1 2 3 4 5 |
|
The background can be java, php, nodejs, etc. For data processing, use the time onmessage event to perform front-end processing on the returned value.
1 2 3 |
|
I hope this article will be helpful to everyone’s JavaScript programming design.