04_01_Ajax+HTTP04_Cross-domain and JSONP

Original policy and cross-domain

Same origin: If the protocol, domain name and port of two pages are the same, then the two pages have the same origin.

Same origin policy

Same origin policy (English full name Same origin policy) is a security feature provided by browsers.

The concept given by MDN official: The same-origin policy restricts how documents or scripts loaded from the same source interact with resources from another source. This is an important security mechanism for isolating potentially malicious files.

[Popular understanding: The browser stipulates that the JavaScript of website A does not allow resource interaction with website C that is not of the same origin.

For example: Unable to read Cookie, LocalStorage and IndexedDB of non-original web pages. Unable to access the DOM of non-original web pages. Unable to send Ajax requests to non-original web addresses]

Cross-domain

Homology means that the protocol, domain name, and port of the two URLs are the same; otherwise, they are cross-domain.

The root cause of cross-domain occurrence: the browser’s same-origin policy does not allow resource interaction between non-original URLs.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/jquery.js"></script>
</head>

<body>
  <script>
    $.ajax({
      method: 'GET',
      url: 'http://ajax.frontend.itheima.net:3006/api/jsonp',
      data: {
        name: 'zs',
        age: 20
      },
      success: function (res) {
        console.log(res)
      }
    })
  </script>
</body>
</html>

Implementing cross-domain data requests

Nowadays, the two most important solutions for implementing cross-domain data requests are JSONP and CORS. JSONP: It appeared early and has good compatibility (compatible with lower versions of IE). It is a temporary solution that front-end programmers are forced to come up with in order to solve cross-domain problems. The disadvantage is that it only supports GET requests and does not support POST requests.

CORS: Appeared later, it is a W3C standard and is the fundamental solution for cross-domain Ajax requests. Supports GET and POST requests. The disadvantage is that it is not compatible with some lower version browsers.

JSONP

Basic concepts

JSONP (JSON with Padding) is a “usage pattern” of JSON that can be used to solve the problem of cross-domain data access in mainstream browsers.

Due to browser origin policy restrictions, non-original interface data cannot be requested through Ajax in web pages. However, the