gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:10:33 24 4
gpt4 key购买 nike

我正在尝试显示从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com