Cross-domain: Use JSONP and WebSocket to achieve cross-domain access

Cross-domain basic knowledge points: Cross-domain knowledge points

Four ways for iframe to achieve cross-domain: Four ways for iframe to achieve cross-domain

Note: The virtual host used in this article is also configured in the iframe above.

Table of Contents

JSONP cross domain

Introduction to JSONP

Cross-domain experiments:

WebSocket cross domain

Introduction to websockets

Cross-domain experiments


JSONP cross-domain

JSONP Introduction

If cross-domain is not involved, the front-end usually obtains data from the server in JSON format. However, this solution is not feasible when cross-domain. However, the JSON book can be shared across domains after simple processing. This is JSONP (JSON with Padding). )plan

You can do some padding before and after the JSON string (this is where the name JSONP comes from), and you can turn it into a piece of javascript code.

JSONP is a common method for cross-origin communication between servers and clients.

The biggest feature is that it is simple and easy to use, there are no compatibility issues, all old browsers support it, and the server-side modification is very small.

Here’s how it does it:

Method 1: When passing parameter JSON data through a function, you need to define the callback function (Callback) in advance, and then load the JSON code through ““. Zhang callback function gets the JSON data

Method 2: Another way is to assign the data to a variable through an assignment statement, which can also introduce JSON data into the current Javascript execution environment.

shortcoming:

  1. Transferring little data

  2. Only supports get transmission (similar to the status of RIP protocol)

The first step is to add a