gpt4 book ai didi

javascript - 如何在Jquery中访问JSON对象?

转载 作者:行者123 更新时间:2023-12-02 14:05:11 25 4
gpt4 key购买 nike

我在 Php 中使用了 Mongodb,我想通过 ajax 调用从 mongo 集合中检索文档,所以我尝试了以下方法,但我在 jquery 中访问 json 对象时遇到了困难。Jquery代码

$('select[name=trendsName]').change(function(){

$.ajax({
url:'getTrendsFullInfo.php',
type: 'POST',
dataType: 'json',
data: {trendsName: $(this).val(), collectionName:'trends_collection'},

success: function(res){
for(var i = 0; i < res.trendsArr['LSM'].length; i++){
$('.resArea').append(res.trendsArr['LSM'][i]);
}
}
});

});

getTrendsFullInfo.php

$finalResultArr = array();
if(isset($_REQUEST['trendsName']) && isset($_REQUEST['collectionName'])):
$status = "Sucessfully Retrived From ".$_REQUEST['collectionName']." Record";
$finalResultArr['LSM'] = array(
'10-12' => 237,
'13-15' => 565,
'16-18' => 825);
$outputArr = array('status'=>$status, 'trendsArr'=>$finalResultArr);

echo json_encode($outputArr);
endif;

如何在jquery中访问trendsArr对象?

最佳答案

问题是你不能对对象使用 .length ,它只会显示 undefined 。所以使用 for in 因为你不知道你的对象键是什么

$('select[name=trendsName]').change(function(){

$.ajax({
url:'getTrendsFullInfo.php',
type: 'POST',
dataType: 'json',
data: {trendsName: $(this).val(), collectionName:'trends_collection'},

success: function(res){
for(var i in res.trendsArr['LSM']){
console.log(" Key => "+ i +" && Value => "+ res.trendsArr['LSM'][i]);
$('.resArea').append(res.trendsArr['LSM'][i]);
}
}
});

});

关于javascript - 如何在Jquery中访问JSON对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40103732/

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