JSON PHP


目录

    显示目录


JSON 的常见用途是从 Web 服务器读取数据, 并将数据显示在网页中。

本章将教你如何在之间交换 JSON 数据 客户端和 PHP 服务器。


PHP 文件

PHP 有一些内置函数来处理 JSON。

PHP中的对象可以使用PHP函数转换为JSON json_encode()

PHP文件

 <?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New 
  York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>

客户端 JavaScript

这是客户端上的 JavaScript,使用 AJAX 调用来请求 PHP 上面示例中的文件:

例子

使用 JSON.parse() 将结果转换为 JavaScript 对象:

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();
</script>

</body>
</html>


PHP 数组

PHP中的数组在使用PHP函数时也会被转换为JSON json_encode()

PHP文件

 <?php
$myArr = array("John", "Mary", "Peter", "Sally");
$myJSON = json_encode($myArr);
echo $myJSON;
?>

客户端 JavaScript

这是客户端上的 JavaScript,使用 AJAX 调用来请求 PHP 上面数组示例中的文件:

例子

使用 JSON.parse() 将结果转换为 JavaScript 数组:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p>Convert the data into a JavaScript array:</p>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php");
xmlhttp.send();
</script>

</body>
</html>

PHP数据库

PHP 是一种服务器端编程语言,可用于访问数据库。

假设您的服务器上有一个数据库,并且您想要向 它来自客户端,您在其中请求名为的表中的前 10 行 “顾客”。

在客户端上,创建一个描述要返回的行数的 JSON 对象。

在向服务器发送请求之前,将 JSON 对象转换为 字符串并将其作为参数发送到 PHP 页面的 url:

例子

使用 JSON.stringify() 将 JavaScript 对象转换为 JSON:

const limit = {"limit":10};
const dbParam = JSON.stringify(limit);
xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xmlhttp.open("GET","json_demo_db.php?x=" + dbParam);
xmlhttp.send();

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p>The JSON received from the PHP file:</p>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({"limit":10});

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>

</body>
</html>

示例解释:

  • 定义一个包含“限制”属性和值的对象。

  • 将对象转换为 JSON 字符串。

  • 向 PHP 文件发送请求,并以 JSON 字符串作为参数。

  • 等待请求返回结果(JSON 格式)

  • 显示从 PHP 文件接收到的结果。

看一下 PHP 文件:

PHP文件

 <?php
header("Content-Type: application/json; charset=UTF-8");
$obj = 
  json_decode($_GET["x"], false);
  
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
  $stmt = $conn->prepare("SELECT name FROM customers LIMIT ?");
$stmt->bind_param("s", $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
  $outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>

PHP 文件解释:

  • 使用 PHP 函数将请求转换为对象 json_decode()

  • 访问数据库,并用请求的数据填充数组。

  • 将数组添加到对象,并使用以下命令将对象作为 JSON 返回 json_encode() 函数。


使用数据

例子

xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "";
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
 
  document.getElementById("demo").innerHTML = text;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>

<script>
const obj = { "limit":10 };
const dbParam = JSON.stringify(obj);
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  myObj = JSON.parse(this.responseText);
  let text = ""
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>

<p>Try changing the "limit" property from 10 to 5.</p>

</body>
</html>

PHP 方法=POST

向服务器发送数据时,通常最好使用 HTTP POST 方法。

要使用 POST 方法发送 AJAX 请求,请指定方法和正确的标头。

发送到服务器的数据现在必须是 send() 方法的参数:

例子

const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text ="";
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_db_post.php");

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>Use HTTP POST to Get JSON Data from a PHP Server</h2>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  myObj = JSON.parse(this.responseText);
  let text = "";
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_db_post.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>

<p>Try changing the "limit" property from 10 to 5.</p>

</body>
</html>

PHP 文件中的唯一区别是获取传输数据的方法。

PHP文件

使用 $_POST 而不是 $_GET:

 <?php
header("Content-Type: application/json; charset=UTF-8");
  $obj = 
  json_decode($_POST["x"], false);
  
  
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
  $stmt = $conn->prepare("SELECT name FROM customers LIMIT ?");
$stmt->bind_param("s", 
  $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
  $outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>