无法从JSON数组和对象值 [英] Unable to get values from JSON Array and Object

查看:151
本文介绍了无法从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数组和对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆