我正在尝试显示从 jquery post 接收到的数据。但它给我一个错误,说 undefined
我的 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 中我试图警告这个值之一,但它给出错误“未定义”。
这是我的 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);
关于javascript - 通过jquery显示php json编码数组的值时出现未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26908923/