jQuery $.each 对应 $.getJSON |无法从多维数组中获取值
jQuery $.each for $.getJSON | Not being able to grab values from multidimensional array
我希望我的 jQuery 代码与底部提供的 PHP 代码执行相同的操作, 但是 1.5 天后,我还没有找到任何有用的信息。
<script>
$(document).ready(function(){
var studNt = $.getJSON('http://127.0.0.1/includes/klradGetNt.php/');
studNt = studNt.emp
studNt = studNt.id1;
$.each(studNt.stud, function (key, value){
// alert("student id: "+ value +".");
});
});
</script>
var studNt 检索
{
"emp": {
"id1": {
"stud": [
"1",
"7"
]
},
"id2": {
"stud": [
"5"
]
}
}
}
我在 PHP 中编写的代码可以很好地完成我需要它做的事情。
在获得 Json 文件后,这就是我想要的,但是在 jQuery:
$data[] = array();
$data = file_get_contents("http://127.0.0.1/includes/klradGetNt.php/");
$data = json_decode($data, true);
foreach ($data['emp']['id1']['stud'] as $key => $value){
echo 'student: '. $value .'. ';
}
什么phpreturns:
student: 1. student: 7.
这些天我也看了其他帖子,还是没看懂。
任何在正确方向上的帮助都非常感激并且谢谢!
从 AJAX 调用返回的结构是一个对象,而不是数组。这可能就是您的研究工作没有找到答案的原因。
与您显示的 PHP 等效的 JS 代码将通过键访问对象(及其属性中的子对象),然后在 [=13] 上使用 forEach()
循环=] 数组,像这样:
studNt.emp.id1.stud.forEach(value => console.log(`student: ${value}`);
另请注意,您需要将任何依赖于 AJAX 请求(在 $.getJSON()
中使用)的响应的逻辑放在回调参数中,或从从 $.getJSON()
.
返回的 jqXHR 对象
话虽如此,您的完整代码块应如下所示:
jQuery($ => {
$.getJSON('http://127.0.0.1/includes/klradGetNt.php/', studNt => {
studNt.emp.id1.stud.forEach(value => {
console.log(`student: ${value}`);
})
});
});
我希望我的 jQuery 代码与底部提供的 PHP 代码执行相同的操作, 但是 1.5 天后,我还没有找到任何有用的信息。
<script>
$(document).ready(function(){
var studNt = $.getJSON('http://127.0.0.1/includes/klradGetNt.php/');
studNt = studNt.emp
studNt = studNt.id1;
$.each(studNt.stud, function (key, value){
// alert("student id: "+ value +".");
});
});
</script>
var studNt 检索
{
"emp": {
"id1": {
"stud": [
"1",
"7"
]
},
"id2": {
"stud": [
"5"
]
}
}
}
我在 PHP 中编写的代码可以很好地完成我需要它做的事情。 在获得 Json 文件后,这就是我想要的,但是在 jQuery:
$data[] = array();
$data = file_get_contents("http://127.0.0.1/includes/klradGetNt.php/");
$data = json_decode($data, true);
foreach ($data['emp']['id1']['stud'] as $key => $value){
echo 'student: '. $value .'. ';
}
什么phpreturns:
student: 1. student: 7.
这些天我也看了其他帖子,还是没看懂。
任何在正确方向上的帮助都非常感激并且谢谢!
从 AJAX 调用返回的结构是一个对象,而不是数组。这可能就是您的研究工作没有找到答案的原因。
与您显示的 PHP 等效的 JS 代码将通过键访问对象(及其属性中的子对象),然后在 [=13] 上使用 forEach()
循环=] 数组,像这样:
studNt.emp.id1.stud.forEach(value => console.log(`student: ${value}`);
另请注意,您需要将任何依赖于 AJAX 请求(在 $.getJSON()
中使用)的响应的逻辑放在回调参数中,或从从 $.getJSON()
.
话虽如此,您的完整代码块应如下所示:
jQuery($ => {
$.getJSON('http://127.0.0.1/includes/klradGetNt.php/', studNt => {
studNt.emp.id1.stud.forEach(value => {
console.log(`student: ${value}`);
})
});
});