我使用
json_encode
进行输出以发送到 javascript,使用此代码。
<?php
include "Connection.php";
$syntax_query = "select * from product";
$thisExecuter = mysqli_query($conn, $syntax_query);
$result = array();
while($row = mysqli_fetch_assoc($thisExecuter)){
array_push(
$result,
array(
"id" => $row["product_id"],
"name" => $row["product_name"]
)
);
}
echo json_encode($result);
?>
所以输出显示如下:
[
{ "id": "121353568", "name": "Baju Casual - Black" },
{ "id": "556903232", "name": "Tas LV - Red" },
{ "id": "795953280", "name": "Sword - Wood" },
{ "id": "834032960", "name": "Scooter - Iron Plate" }
]
Javascript 代码如下:
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var obj = this.responseText;
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
obj.id
不起作用,输出显示“未定义”。
当我想调用 Php 文件并从与下面相同的内容获取响应时,我使用 ajax 调用,如我所示,尝试一次。在使用 Ajax 之前,您必须需要将 jquery 导入到调用文件中。
如果导入了Jquery则忽略这些步骤
以下是步骤,
现在,这是调用 PHP 文件并获取响应的 ajax 示例
function showHint() {
//since you have used GET method I have used here GET but You can use POST also here
$.ajax({
url: 'Download.php',
type: 'get',
//if any value you want to pass then uncomment below line
// data: {'name_to_pass':'value'},
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
success: function(res)
{
// open DevTool console to see results
console.log(JSON.parse(res));
}
});
}
也许您需要在响应中使用 JSON.parse,例如
JSON.parse(this.responseText)
。
我还可以看到结果是一个数组,所以你需要迭代
obj
obj.forEach(item => {
document.getElement("txtHint").innerHTML = item.id;
});
您应该将响应类型定义为 json
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
**var obj = this.responseText;**
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
当您获得responseText时,它是文本,而不是对象。
var obj = this.responseText;
应该是let obj = JSON.parse(this.responseText);
然后你就可以将 obj.id 作为属性来访问。