javascript - jQuery 和 JSON 的问题

标签 javascript php jquery json

我正在尝试查询 MySQL 数据库并使用 JSON 将结果放入 jQuery,因为我需要做图形。

我的问题是当我操作 JSON 时。

我现在的代码: index.php

$(function ($) {

    $("#formulario").submit(function () {

        var nome = $("#nome").val();

        $("#status").html("<img src='loader.gif' alt='Enviando' />");
        $.post('envia.php', {
            nome: nome
        }, function (resposta) {
            $("#status").slideDown();
            if (resposta != false) {
                $("#status").html(resposta);
            } else {
                $("#nome").val("");
            }
        });
    });
});

envia.php(查询仅用于测试)

require_once("conecta.php");

$nome = $_POST["nome"];
$culturas = array();
$resultado = mysqli_query($conexao, "select *from mandioca_iea where  mandioca_iea_id=1");

while ($cultura = mysqli_fetch_assoc($resultado)) {
    array_push($culturas, $cultura);
}

echo json_encode($culturas);

如果我以这种方式测试代码: 在 div="status"中出现:

[{"mandioca_iea_id":"1","man_ins_area_00":"0","man_ins_prod_00":"0","man_ins_area_05":"0","man_ins_prod_05":"0","man_ins_area_10":"0","man_ins_prod_10":"0","man_ins_area_13":"0","man_ins_prod_13":"0","id_cid":"1","id_cult":"1"}] OK,It works

但是当我尝试使用此代码访问“字段”时,它不起作用:

$.post('envia.php', {nome: nome}, function(resposta) {
    for(var i=0; i<resposta.length; i++) {
        var registro = resposta[i];
        console.log(registro.man_ins_area_10); 
    }
});

OBS:我也尝试过 resposta = $.parseJSON(resposta)

在网络浏览器的控制台中,结果是:

228 undefined,换句话说,发生“循环”228次,所有“变量”都未定义。

有人知道为什么会发生这种情况吗?

最佳答案

尝试使用正确的属性。由于您的json数据中没有iea_id,因此它没有提供任何内容。

 var resposta= [{"mandioca_iea_id":"1","man_ins_area_00":"0","man_ins_prod_00":"0","man_ins_area_05":"0","man_ins_prod_05":"0","man_ins_area_10":"0","man_ins_prod_10":"0","man_ins_area_13":"0","man_ins_prod_13":"0","id_cid":"1","id_cult":"1"}] 
     for(var i=0; i<resposta.length; i++) {
            var registro = resposta[i];
            console.log(registro.mandioca_iea_id); //it should give 1
        }

更新:

$.post('envia.php', {nome: nome}, function(resposta) {
    console.log(resposta);
    var resposta=JSON.parse(resposta);
    for(var i=0; i<resposta.length; i++) {
        var registro = resposta[i];
        console.log(registro.customerLat); 
    }
});

关于javascript - jQuery 和 JSON 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28236910/

相关文章:

php - 自定义添加到购物车按钮以将多个产品添加到购物车中,数量为 :woocommerce

javascript - 将 PHP 变量转换为带有转义字符的 Javascript 变量

javascript - 显示移动窗口时在 Bootstrap 导航栏中附加搜索栏?

javascript - 如何实现第三方Javascript库?

javascript - 使用 javascript 媒体查询应用样式

Javascript window.location.href - 刷新页面而不是重定向

jquery - 使用 jQuery/AJAX 解码 JSON

javascript - 我对 for 循环中的 javascript let 和 var 感到困惑?

php - 将 3 个 MYSQL 查询优化为一个

javascript - 如何将事件绑定(bind)到 Tabbing Off 元素?