JSON编码MySQL结果,然后使用jQuery读取 [英] JSON encode MySQL results then read using jQuery

查看:117
本文介绍了JSON编码MySQL结果,然后使用jQuery读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a database table with some rows that I want to fetch using PHP and then encode them using JSON.

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

Currently, my database structure is the following:

idcomponente | quantidade

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

After fetching the values in PHP, I want to know how can I encode them using JSON (with multiple rows, using the same names) so I can read them using jQuery.post().

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

预先感谢

到目前为止,我做到了:

So far, I made this:

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


记录此:


Logs this:

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

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

Now how can I go through each row and fetch their properties? (data.componente, data.quantidade)

推荐答案

在这里,我尝试给您一些想法.

Here I try to give you some idea.

使用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

In 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');

这篇关于JSON编码MySQL结果,然后使用jQuery读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆