通过jquery显示php json编码数组的值时出现未定义错误

时间:2014-11-13 12:29:21

标签: javascript php jquery json

我正在尝试显示从jquery帖子收到的数据。但它给我一个错误说未定义

我的php json编码数组就是这个。

[{"matId":"7","matName":"test","matBrand":"est","matPackaging":"1","matWidth":"434","matHeight":"23","matLength":"23","matWeight":"23","matArea":"23","matVolume":"23","matPerPack":"32","supplier1":"19","supplier2":"19","supplier3":"19","requiredInPhase":"","stockItem":"1"}]

然后在jquery中我试图提醒其中一个值,但它给出了错误' undefined'。

这是我的jquery代码

$('#matId').on('change', function() {
            var matId = $(this).val();
            $.post('<?php echo base_url() . 'display_mat_details'; ?>', {matId: matId}, function(redata) {
                var obj = $.parseJSON(redata);
                alert(obj.matId);
            });
        });

4 个答案:

答案 0 :(得分:1)

这是因为您的JSON是一个包含对象的数组...删除JSON周围的方括号。

答案 1 :(得分:1)

您的数据包含在[]数组中。因此,您需要使用[0]从数组中获取第一个对象

$('#matId').on('change', function() {
  var matId = $(this).val();
  $.post('<?php echo base_url() . '
    display_mat_details '; ?>', {
      matId: matId
    }, function(redata) {
      var obj = $.parseJSON(redata);
      alert(obj[0].matId);
    });
});

示例:

&#13;
&#13;
var str = [{"matId":"7","matName":"test","matBrand":"est","matPackaging":"1","matWidth":"434","matHeight":"23","matLength":"23","matWeight":"23","matArea":"23","matVolume":"23","matPerPack":"32","supplier1":"19","supplier2":"19","supplier3":"19","requiredInPhase":"","stockItem":"1"}];
alert(str[0].matId);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用此代码 将obj.matId替换为obj[0].matId

  $('#matId').on('change', function() {
                var matId = $(this).val();
                $.post('<?php echo base_url() . 'display_mat_details'; ?>', {matId: matId}, function(redata) {
                   // var obj = $.parseJSON(redata);// error here structure of redata is wrong
                   // alert(obj[0].matId);
                    alert(redata[0].matId);
                });
            });

答案 3 :(得分:1)

并使用

$.parseJSON()

你的数组结构应该是这样的

var Content = '{"matId":"7","matName":"test","matBrand":"est","matPackaging":"1","matWidth":"434","matHeight":"23","matLength":"23","matWeight":"23","matArea":"23","matVolume":"23","matPerPack":"32","supplier1":"19","supplier2":"19","supplier3":"19","requiredInPhase":"","stockItem":"1"}';

var obj = $.parseJSON(Content);
alert(obj.matId);