Home >Web Front-end >JS Tutorial >Detailed explanation of JSON and JSONP in JS

Detailed explanation of JSON and JSONP in JS

青灯夜游
青灯夜游forward
2020-10-23 17:52:413123browse

Detailed explanation of JSON and JSONP in JS

Simply using json cannot support cross-domain resource requests. In order to solve this problem, the jsonp data interaction protocol needs to be used. As we all know, the call of js files is not restricted by whether it is cross-domain or not. Therefore, if you want to access data cross-domain through the pure web side, you can only try to encapsulate the json data into a js format file on the remote server for the client to call and Further processing, this is the principle of jsonp protocol.

JSON and JSONP

JSONP is a way to send JSON data without worrying about cross-domain issues. JSONP does not use the XMLHttpRequest object. JSONP uses the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag instead.
Due to cross-domain policies, requesting files from another domain may cause problems. Requesting an external script from another domain does not have this problem. JSONP takes advantage of this and requests files using script tags instead of XMLHttpRequest objects.

<script src="demo_jsonp.php">

Server file

The file on the server wraps the result in a function call:

<?php
$myJSON = &#39;{"name":"John", "age":30, "city":"New York"}&#39;;
echo "myFunc(".$myJSON.");";
?>

The result is returned by name A call to the function "myFunc" with JSON data as a parameter. Make sure the functionality exists on the client.

JavaScript Function

The function named "myFunc" is located on the client side and is ready to process JSON data:

function myFunc(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.send("x=" + dbParam);

Create dynamic script tag

Depending on where you place the script tag, the above example will execute the "myFunc" function when the page loads, which is not very satisfactory . The script tag should only be created when needed:
Create and insert the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag when the button is clicked:

function clickButton() {
  var s = document.createElement("script");
  s.src = "demo_jsonp.php";  
  document.body.appendChild(s);
}

Dynamic JSONP results

The above example is still very static. Make the example dynamic by sending JSON to a php file and have the php file return a JSON object based on the information obtained.
PHP file

<?phpheader("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);echo "myFunc(".json_encode($outp).")";
?>

PHP file explanation:
Use the PHP function json_decode() to convert the request into an object.
Access the database and populate the array with the requested data.
Add an array to an object.
Use the json_encode() function to convert the array to JSON.
Wrap "myFunc()" around the return object

JavaScript example:

function clickButton() {
  var obj, s
  obj = { table: "products", limit: 10 };
  s = document.createElement("script");
  s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj);
  document.body.appendChild(s);
}
function myFunc(myObj) {  var x, txt = "";  for (x in myObj) {
    txt += myObj[x].name + "
";
  }
  document.getElementById("demo").innerHTML = txt;
}

Callback function

How do you make the server file call the correct function when you have no control over the server file? Sometimes the server file provides a callback function as a parameter:
php file will call the function you pass as a callback parameter:
PHP file:

<?php
$callback = trim($_GET(&#39;callback&#39;));
$myJSON = &#39;{ "name":"John", "age":30, "city":"New York" }&#39;;
echo $callback."(".$myJSON.");";
?>

javascript:

function clickButton() {
  var s = document.createElement("script");
  s.src = "jsonp_demo_db.php?callback=myDisplayFunction";  
  document.body.appendChild(s);
}

More programming related For knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Detailed explanation of JSON and JSONP in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete