JSON 对 MySQL 结果进行编码,然后使用 jQuery 读取


JSON encode MySQL results then read using jQuery

我有一个数据库表,其中包含一些我想使用 PHP 获取的行,然后使用 JSON 对它们进行编码。

目前,我的数据库结构如下:

idcomponente | quantidade

在 PHP 中获取值后,我想知道如何使用 JSON(具有多行,使用相同的名称)对它们进行编码,以便我可以使用 jQuery.post() 读取它们。

$.post('test.php',{id:id},function(data){
    //READ data HERE
});

提前致谢

编辑:

到目前为止,我做了这个:

$.post('edit/producomponentes.php',{id:id},function(data){
    console.log(data);
});

记录以下内容:

[Object { componente="1", quantidade="2"}, Object { componente="3", quantidade="3"}]

现在,如何浏览每一行并获取其属性?(data.componente, data.quantidade)

在这里,我试着给你一些想法。

在 PHP 中使用key => value对创建关联数组,例如

$data = array('id' => 1, 'quat' => 10, 'id' => 2, 'quat' => 20)

然后像json_encode()一样发送

header('Content-type: application/json');  // don't miss it
echo json_encode(array('data' => $data));

在jQuery中

$.post('edit/producomponentes.php',{id:id},function(response){
    //READ data HERE.
    console.log(response.data); // you will get a json Object
}, 'json');
     ^-------- set dataType as json, then you don't any extra parse effort

根据编辑

 $.post('edit/producomponentes.php',{id:id},function(data){
        $.each(data, function(index, value) {
           console.log(value.componente);
           console.log(value.quantidade);
        });
    }, 'json');

在测试中.php

$id = $_POST['id']; // if is 'id' passed to fetch one row
$db = new mysqli(HOST,USER,PASS,DB_NAME);
$q = "SELECT * FROM table WHERE id='$id'";
$result = $db->query($q);

编辑正确的标头以用于 json 响应

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($result->fetch_all(MYSQLI_ASSOC));
$result->close();
$db->close();

在 JavaScript 中

$.post('test.php',{id:id},function(data){
    console.log(data); // data is already a js object
},'json'); // specify the data type you expect

您可以将每一行放在数组中,然后在最终数组上运行json_encode()以获取一个大的 JSON 对象。

参考 - http://php.net/manual/en/function.json-encode.php

使用 JSON.parse 将数据作为对象获取,例如

var object1 = JSON.parse(data);
alert(object1.property1);

要在 PHP 上进行编码,请使用

json_encode($result); //assuming you're getting a result set.

对结果集进行编码,以及

echo json_encode($result);

将其打印到文档正文,以便您可以使用 jQuery 获取结果数据

文档在这里

你需要多次测试它,耐心等待,并在PHP端使用echo和客户端的alert()来计算你的值。

相关文章: