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


undifined error when displaying values of php json encoded array by jquery

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

我的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);
            });
        });

您的数据包含在作为数组的[]中。因此,您需要使用[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);
    });
});

示例:

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

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

并使用

$.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);

使用此代码用obj[0].matId 代替obj.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);
                });
            });