define

The same-origin policy

First, we need to understand what the same origin policy is. Let’s look at baidu Baike’s explanation:

The same origin policy, which is a famous security policy proposed by Netscape. This strategy is now used by all browsers that support JavaScript. Same name means same domain name, same protocol, same port. When two tabs of a browser open baidu and Google pages respectively, when a Baidu browser executes a script, it checks which page the script belongs to, that is, check whether the script is of the same origin. Only scripts with the same origin as Baidu are executed.Copy the code

In summary, due to browser security restrictions, data cannot be requested directly across domains, including different root domains, secondary domains, or different ports, unless the destination domain authorizes access. If you want to solve the same origin policy and implement transport, you need to cross domain. There are many ways to cross domains, and JSONP is one of them.

Specific want to learn more, you can see nguyen other teacher’s article, very detailed explanation: www.ruanyifeng.com/blog/2016/0…

The generation of the json

We found that the js file on a Web page is not affected by whether it is cross-domain or not. Moreover, we also found that any tag with the attribute “SRC” has cross-domain capability, such as <\script>, <\img>, <\iframe>.

There is a pure character data format called JSON that can describe complex data concisely and is supported by native JS.

So a cross-domain solution emerged. We can call js files dynamically generated on cross-domain servers, that is, call JSON files to get the data we need.

An informal transport protocol, known as JSONP, evolved. This protocol allows the user to pass a callback parameter to the server, which then wraps the JSON data as a function name when the server returns the data. The client receives the response and performs a callback and does whatever it needs to do with the data.

With that said, let’s summarize what JSONP is: By dynamically creating a Script tag whose SCR points to a non-cognate URL and passing a callback parameter to the server, the server returns a function call with the callback parameter as the function name and a set of parameters. The page executes a callback and processes the data when it receives the response.

Next, we will implement the complete process of JSONP.

To realize the json

First, we have a requester and a responder. The requester is the front end of one web page, i.e. the browser, and the responder is the back end of another web page, i.e. the server. The two web pages have different sources.

Here we assume that the browser page displays a number 100 and a farming instead of button, the server storing the page shows the number of requirements at the time of each farm button, the browser display number minus one, and the server storage after losing the number, at the time of the next open display after reduction of Numbers. This is the process of sending requests and receiving responses across domains to servers of non-homologous sites. Requestor: http://fang.com:8001 Responder: http://zeng.com:8002

Write the HTML first:


button.addEventListener(
  'click',(e)=>{
    let script = document.createElement('script')// Create the script tag
    let functionName = 'fang' + parseInt(Math.random()*10000000.10)// Set the name of the calling function
    window[functionName] = function(result){
      if(result === 'success'){
        amount.innerText = amount.innerText - 1
      }else{

      }
    }
    script.src = `http://zeng.com:8002/pay?callback${functionName} `
    document.body.appendChild(script)// Insert script tags that can send cross-domain requests into HTML
    script.onload = function(e){
      e.currentTarget.remove()
      delete window[functionName]
    }
    script.onerror = function(){
      alert('fail')
      e.currentTarget.remove()
      delete window[functionName]
    }
    // Delete the script tag after the transfer is complete})Copy the code

Set up the server, you can achieve the function. This is the process of sending cross-domain and response using JSONP.

Advantages and disadvantages of JSONP

advantages

  • JSONP can implement cross-domain transport across the same origin policy, unlike Ajax requests implemented by XMLHttpRequest objects that are constrained by the same origin policy
  • JSONP is more compatible, runs in older browsers and does not require XMLHttpRequest or ActiveX support
  • After the request is complete, the result can be returned by calling callback. Gives permission to the callback method to the caller

disadvantages

  • It only supports GET requests, not other types of HTTP requests such as POST, because the SCR of script tags can only make GET requests
  • It only supports cross-domain HTTP requests and does not solve the problem of how to make JavaScript calls between two pages in different domains.
  • Jsonp does not return various HTTP status codes when a call fails.
  • Lack of security. If the service that provides JSONP has a page injection vulnerability, that is, the javascript it returns is controlled by someone, then all websites that call the JSONP will have a vulnerability, so the risk is not just one domain name.

If you find my articles useful, please like them and follow them. Also, please visit my personal blog github.com/BokFang