简体   繁体   English

json_encode用html打印数据

[英]json_encode prints data in html

I'm trying to pass Database table from PHP (using Object-Oriented approach) to Javascript using Ajax ( json_encode ) which I've done successfully. 我正在尝试使用成功完成的Ajax( json_encode )将数据库表从PHP(使用面向对象的方法)传递给Javascript。 The problem, however, is that the values that are inside the $data variable are printed in my body tag with a huge whitespace after it. 但是,问题在于$ data变量中的值会在我的body标签中显示,并带有巨大的空格。

Server Side: 服务器端:

<?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();
?>

Client side: 客户端:

$(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);
}

Output (Note that body tags aren't being outputted): 输出(请注意,不会输出body标签):

<body>
    "[{"id":"1","0":"1","name":"john","1":"john"}, 
     {"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>

Is there any way to prevent echo json_encode from printing data in HTML if all I want to do is pass it from PHP to javascript? 如果我要做的就是将其从PHP传递到javascript,是否有任何方法可以防止echo json_encode在HTML中打印数据?

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

header('Content-Type: application/json');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM