Home >Web Front-end >JS Tutorial >Use JavaScript to implement various cross-domain methods_Basic knowledge

Use JavaScript to implement various cross-domain methods_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:34:071082browse

1. Some concepts

①Traditional Ajax: interactive data format - custom string or XML description;

Cross-domain - solved through server-side proxy.

②Today’s best solution: use JSON format to transmit data, and use JSONP to cross domains.

③JSON: A data exchange format. Based on plain text and supported by native JS.

Format: Two data type descriptors: curly brackets { } and square brackets [ ]. The delimiter comma, the mapping character colon, and the definer character are double quotes.

④JSONP: A cross-domain data interaction protocol, unofficial.

 1. Web pages call js files, which can cross domains. Extension: Any tag with the src attribute has cross-domain capabilities.

 2. The cross-domain server dynamically generates data and stores it in a js file (usually with a json suffix) for client calls.

 3. In order to facilitate the client to use data, an informal transmission protocol is formed, called JSONP. The focus of this protocol is to allow users to pass a callback parameter to the server, and then when the server returns data, this callback parameter is used as a function name to wrap the JSON data, so that the client can customize its own function to automatically process the returned data.


2. JSONP implementation

Example 1 - Unilateral reception by the client:

①Client - Create a function object in the client settings, the name can be callFunc, used to receive the js data from the server and process it.
The core of js data is: calling the callFunc function is accompanied by parameters, which are the values ​​of the data objects.

Copy code The code is as follows: