【发布时间】:2018-09-15 15:27:55
【问题描述】:
我正在尝试使用我已经成功完成的 Ajax (json_encode) 将数据库表从 PHP(使用面向对象的方法)传递到 Javascript。然而,问题在于 $data 变量中的值打印在我的 body 标记中,后面有一个巨大的空格。
服务器端:
<?php
require_once "Database.php";
Class Product extends Database
{
public function getAllProducts(){
$sql = $this->connectDB()->query("SELECT * FROM product");
while($row = $sql->fetch()) {
$data[] = $row;
}
echo json_encode($data);
}
}
$p = new Product();
$p->getAllProducts();
?>
客户端:
$(function() {
getProductData();
});
function getProductData(){
$.ajax({
url: "Product.php",
type: "get",
dataType: "json",
success: successAjax,
error: errorAjax,
complete: function(xhr, status) {
console.log(xhr);
console.log(status);
}
});
}
function successAjax($jsonarray){
console.log($jsonarray);
}
输出(注意身体标签没有被输出):
<body>
"[{"id":"1","0":"1","name":"john","1":"john"},
{"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>
如果我只想将它从 PHP 传递到 javascript,有什么方法可以防止 echo json_encode 在 HTML 中打印数据?
【问题讨论】:
-
你能分享一下Product.php的完整代码吗?您在 Product.php 中保留了一些 HTML 文本。
-
你可以改成这样:
return json_encode($data);你也可能需要将返回的值保存到一个变量中。 -
@RinsadAhmed 我已经编辑了帖子以包含整个 Product.php。仅此而已。
-
@enxaneta
return json_encode($data)返回Object "parsererror" SyntaxError: Unexpected end of JSON input -
所以你只得到一个额外的 标签?
标签: javascript php html ajax