json_encode以html格式打印数据

问题描述 投票:0回答:1

我正在尝试使用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>

有没有办法阻止回应json_encode打印HTML中的数据,如果我想做的就是将它从PHP传递给javascript?

javascript php html ajax
1个回答
0
投票

尝试在product.php上首先发送json http标头

header('Content-Type: application/json');
© www.soinside.com 2019 - 2024. All rights reserved.