无法从JSON数组和对象值

编程入门 行业动态 更新时间:2024-10-24 14:27:26
本文介绍了无法从JSON数组和对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的JavaScript和PHP,我能做到的阿贾克斯调用来获取一个数组。但是当我想显示显示每个对象的我无法价值观这样做。

In my Javascript and PHP, I've manage to do an .ajax call to get an array. However when I want to display the display the values of each object I'm unable to do so.

PHP:

$request = '{"request_id":' .$requestId. ', "reqName":"' .$requestName. '", "reqSubject":' .json_encode($requestSubjects). '}'; array_push($requestArray, $request); echo json_encode($requestArray);

使用Javascript:

Javascript:

$.ajax({ type: "POST", url: serverURL + "getTutorRequestsProcess.php", data: sendTutId, dataType: "json", success: function(data){ localStorage.setItem('pending', JSON.stringify(data)); pending = JSON.parse(localStorage.getItem('pending')); console.log(pending); }, error: function(jqXHR, textStatus, errorThrown){ alert('Unable to retrieve requests.', null, 'Error','Done'); } });

所以,当我的console.log(待定)它看起来是这样的:

["{"request_id":13, "reqName":"Rin", "reqSubject":["English","A Math"]}", "{"request_id":14, "reqName":"Rin", "reqSubject":["English","E Math"]}"]

当我的console.log(待定[0]),我能够得到的第一个对象:

When I console.log(pending[0]), I'm able to get the first object:

{"request_id":13, "reqName":"Rin", "reqSubject":["English","A Math"]}

然而,当我想要得到像这样的对象的值,的console.log(待定[0] .request_id),它返回一个未定义。

会强烈AP preciate如果有人能告诉我什么地方错了我的codeS。谢谢你。

Would highly appreciate if someone could tell me what's wrong with my codes. Thank you.

编辑:我试图将数据添加到我的localStorage。更新codeS,以反映我在做什么。

I'm trying to add the data into my localStorage. Updated codes to reflect what I'm doing.

更新的Javascript:

Updated Javascript:

$.ajax({ type: "POST", url: serverURL + "getTutorRequestsProcess.php", data: sendTutId, dataType: "json", success: function(data){ localStorage.setItem('pending', JSON.stringify(data)); pending = JSON.parse(localStorage.getItem('pending')); console.log(pending[0]); var response = jQuery.parseJSON(pending[i]); console.log(response.request_id); }, error: function(jqXHR, textStatus, errorThrown){ alert('Unable to retrieve requests.', null, 'Error','Done'); } })

通过OVM和codeseeker作品这两个答案,解决我的问题。这是可悲的,我不能标记既是正确的,因为两者都提供了两种不同的,但有效的解决方案。

推荐答案

。用于访问对象的属性,而 [] 符号用于访问数组值。

. is used for to access object property while [] notation is used for to access array value.

console.log(data[0]['request_id']);

演示

Demo

更新:

试着用 -

var response = jQuery.parseJSON(data0) console.log(response.request_id);

更多推荐

无法从JSON数组和对象值

本文发布于:2023-10-27 03:29:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!