【发布时间】:2021-03-02 13:02:00
【问题描述】:
我正在尝试编写一个使用 php 和 ajax 读取 json 文件的简单演示。在js中我有
// initial entry point
function main(){
var button = document.getElementById("button");
button.addEventListener("click",test);
button.addEventListener("click",getSummary);
}
function test(){
console.log("button was clicked");
}
function getSummary(){
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", processResponse, false);
console.log("sending request");
asyncRequest.open("GET","http://localhost/summary.php",true);
asyncRequest.send(null);
}
function processResponse(){
console.log("processing request");
if(asyncRequest.readyState==4 && asyncRequest.status==200){
console.log(asyncRequest.response);
}
}
summary.php
<?php
$data = readfile("summary.json");
header('Content-Type: text/json;charset=utf-8');
echo json_encode($data);
summary.json
{
"products":[
{
"product":"professional pencil",
"image":"pencil.jpg",
"description":"The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
},
{
"product":"coffee mug",
"image":"coffee_mug.jpg",
"description":"Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
},
{
"product":"programming book",
"image":"programming_book.jpg",
"description":"Learn how to program effectively by reading this book."
}
]
}
当我提出请求时,我在响应结束时收到一个不寻常的706。
curl localhost/summary.php | Select Content -Expand Content | jq 产生
{
"products": [
{
"product": "professional pencil",
"image": "pencil.jpg",
"description": "The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
},
{
"product": "coffee mug",
"image": "coffee_mug.jpg",
"description": "Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
},
{
"product": "programming book",
"image": "programming_book.jpg",
"description": "Learn how to program effectively by reading this book."
}
]
}
706
对此的任何帮助将不胜感激。
【问题讨论】:
-
您是否尝试过逐个输入以查看添加数字的位置?
-
它通常是为一些调试添加的流氓回声
-
706是您编码为 JSON 的内容。您的变量$data不包含您认为的内容,阅读readfile的手册会告诉您原因。 -
使用
$data = file_get_contents("summary.json");