无法从JSON Array和Object获取值

在我的Javascript和PHP中,我设法进行.ajax调用以获取数组。 但是,当我想显示每个对象的值时,我无法这样做。

PHP:

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

使用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(pending)它看起来像这样:

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

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

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

但是当我想得到像这样的对象的值, console.log(pending[0].request_id) ,它返回一个undefined

如果有人能告诉我我的代码有什么问题,我将非常感激。 谢谢。

编辑:我正在尝试将数据添加到我的localStorage。 更新了代码以反映我正在做的事情。

更新的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的答案都有效并解决了我的问题。 令人遗憾的是,我无法将两者都标记为正确,因为它们都提供了两种不同但有效的解决方案。

. 用于访问对象属性,而[]表示法用于访问数组值。

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

演示

更新:

尝试 –

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

问题是,您使用json_encode序列化字符串,而不是真正的PHP类和属性。

生成的json是一个字符串数组,而不是一个对象数组:

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

你想要这样的结果

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

为此,尝试使用这些属性构建标准PHP对象并对其进行序列化。 不要序列化包含json的字符串。

所以在服务器端,用这个替换你的第一行代码,你会很高兴:

 $request = (object)['request_id': $requestId, 'reqName': $requestName, 'reqSubject': ['English', 'A Math']];