Understand the principles and applications of JSONP in one article

Understand the principles and applications of JSONP in one article

What is JSONP

First, let’s talk about the concept of JSON. JSON is a lightweight data transmission format that is widely used in current Web applications. The encoding and parsing of JSON format data are basically implemented in all mainstream languages, so most of the front-end and back-end separated architectures now transmit data in JSON format.

So what is JSONP?

First, let’s talk about the concept of browser homology policy. In order to ensure the security of user access, modern browsers use the homology policy, which means that access to pages from non-homologous sources is not allowed. You can search Baidu for the detailed concept. Here everyone just needs to know that in ajax, requests for non-same-origin URLs are not allowed. For example, a page under www.a.com, the ajax request is not allowed to access a page like www.b.com/c.php.

JSONP is used to solve the cross-domain request problem, so how is it implemented specifically?

JSONP Principle

Ajax requests are affected by the same-origin policy and cross-domain requests are not allowed. However, the link in the src attribute of the script tag can access the cross-domain js script. Using this feature, the server no longer returns data in JSON format, but returns a section of js code that calls a function, which is called in src, thus achieving cross-domain.

JSONP Implementation

1. What happens if a cross-domain request is made in ajax

The front-end code is under the domain www.practice.com and uses ajax to send a cross-domain get request

<!DOCTYPE html>
<html>
<head>
	<title>GoJSONP</title>
</head>
<body>
<script type="text/javascript">
	function jsonhandle(data){
		alert("age:" + data.age + "name:" + data.name);
	}
</script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
</script>
<script type="text/javascript">
	$(document).ready(function(){
		$.ajax({
			type : "get",
			async: false,
			url: "http://www.practice-zhao.com/student.php?id=1",
			type: "json",
			success : function(data) {
				jsonhandle(data);
			}

		});
	});
</script>
</body>
</html>

The backend PHP code is placed under the domain www.practice-zhao.com and simply outputs a piece of data in json format

jsonhandle({

"age" : 15,

"name": "John",

When accessing the front-end code http://www.practice.com/gojsonp/index.html, Chrome reports the following error

It is suggested that URLs from different sources are prohibited from access

2. Use JSONP to remove the ajax request in the front-end code

Added a script tag, the src of which points to the remote.js script under another domain www.practice-zhao.com

<!DOCTYPE html>
<html>
<head>
	<title>GoJSONP</title>
</head>
<body>
<script type="text/javascript">
	function jsonhandle(data){
		alert("age:" + data.age + "name:" + data.name);
	}
</script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
</script>
<script type="text/javascript" src="http://www.practice-zhao.com/remote.js"></script>
</body>
</html>

The cross-domain remote.js script is called here. The remote.js code is as follows:

jsonhandle({
	"age" : 15,
	"name": "John",
})

That is, this remote js code executes the function defined above and pops up a prompt box

3. Modify the front-end code again

The code is as follows:

<!DOCTYPE html>
<html>
<head>
	<title>GoJSONP</title>
</head>
<body>
<script type="text/javascript">
	function jsonhandle(data){
		alert("age:" + data.age + "name:" + data.name);
	}
</script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
</script>
<script type="text/javascript">
	$(document).ready(function(){
		var url = "http://www.practice-zhao.com/student.php?id=1&callback=jsonhandle";
		var obj = $('<script><\/script>');
		obj.attr("src",url);
		$("body").append(obj);
	});
</script>
</body>
</html>

A script tag is dynamically added here, the src points to a cross-domain PHP script, and the above JS function name is passed as the callback parameter, then let's see how the PHP code is written:

<?php
$data = array(
	'age' => 20,
	'name' => 'Zhang San',
);

$callback = $_GET['callback'];

echo $callback."(".json_encode($data).")";
return;

The PHP code returns a JS statement, namely

jsonhandle({
	"age" : 15,
	"name": "Zhang San",
})

When you access the page at this time, a script tag is dynamically added, src points to the PHP script, the returned JS code is executed, and a prompt box pops up successfully.
Therefore, JSONP turns access to cross-domain requests into executing remote JS code. The server no longer returns data in JSON format, but instead returns a function execution code that takes the JSON data as an incoming parameter.

4. Finally, jQuery provides a convenient way to use JSONP

The code is as follows:

<!DOCTYPE html>
<html>
<head>
	<title>GoJSONP</title>
</head>
<body>
<script type="text/javascript" src="jquery-1.8.3.min.js">
</script>
<script type="text/javascript">
	$(document).ready(function(){
		$.ajax({
			type : "get",
			async: false,
			url: "http://www.practice-zhao.com/student.php?id=1",
			dataType: "jsonp",
			jsonp:"callback", //Parameter name of request PHP jsonpCallback: "jsonhandle", //Callback function to be executed success : function(data) {
				alert("age:" + data.age + "name:" + data.name);
			}

		});
	});
</script>
</body>
</html>

The above is the detailed content of understanding the principles and applications of JSONP in one article. For more information about the principles and applications of JSONP, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JSONP principles, understanding and example analysis
  • Analysis of the Principle of Jsonp Cross-Domain Solution
  • Detailed explanation of JSONP principles and application examples
  • JSONP principle and simple implementation
  • In-depth analysis of the jsonp protocol principle
  • In-depth analysis of the principle of JSONP cross-domain
  • JSONP cross-domain principle analysis and implementation introduction
  • JSONP principle and use
  • Using script to make Http cross-domain requests: JSONP implementation principle and code
  • js/ajax cross-access-jsonp principle and example (javascript and jquery implementation code)

<<:  Docker container log analysis

>>:  Detailed explanation of the principle of distributed locks and three implementation methods

Recommend

Example of how to implement value transfer between WeChat mini program pages

Passing values ​​between mini program pages Good ...

Bootstrap 3.0 study notes page layout

This time we will mainly learn about layout, whic...

JavaScript implements long image scrolling effect

This article shares the specific code of JavaScri...

Keepalived implements Nginx load balancing and high availability sample code

Chapter 1: Introduction to keepalived The purpose...

Share CSS writing standards and order [recommended for everyone to use]

CSS writing order 1. Position attributes (positio...

jQuery implements the bouncing ball game

This article shares the specific code of jQuery t...

Some functions of using tcpdump to capture packets in the Linux command line

tcpdump is a flexible and powerful packet capture...

HTML+Sass implements HambergurMenu (hamburger menu)

A few days ago, I watched a video of a foreign gu...

Detailed explanation of custom swiper component in JavaScript

Table of contents Effect display Component Settin...

Web Design: Script Materials Reconstruct User Experience

<br />Original text: http://blog.rexsong.com...

Detailed explanation of Vue.js directive custom instructions

Customize a demo command The syntax of Vue custom...

Details of the underlying data structure of MySQL indexes

Table of contents 1. Index Type 1. B+ Tree 2. Wha...

Vue implements user login switching

This article example shares the specific code of ...

A problem with MySQL 5.5 deployment

MySQL deployment Currently, the company deploys M...