无法从JSON数组和对象中获取值

时间:2022-12-04 16:01:25

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.

在Javascript和PHP中,我成功地执行了.ajax调用来获取数组。但是,当我想显示每个对象的值时,我不能这样做。

PHP:

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');
    }
});

So when I console.log(pending) it looks like this:

当我console.log(pending)看起来是这样的

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

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

当我console.log(pending[0])时,我可以得到第一个对象:

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

However when I want to get the values of the object like so, console.log(pending[0].request_id), it returns an undefined.

但是,当我想获取对象的值时,比如console.log(挂起[0].request_id),它会返回一个未定义的值。

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

如果有人能告诉我我的代码出了什么问题,我将不胜感激。谢谢你!

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

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

Updated 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[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');
    }
})

Both answers by OVM and Codeseeker works and solved my question. It's sad that I can't mark both as correct since both of them have provided two different but valid solutions.

OVM和Codeseeker的回答都能解决我的问题。遗憾的是,我不能将两者都标记为正确的,因为它们都提供了两个不同但有效的解决方案。

2 个解决方案

#1


0  

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

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

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

Demo

演示

Update:

更新:

Try with -

试一试,

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

#2


1  

The problem is, that you are serializing strings with json_encode, not real PHP classes and properties.

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

This resulting json is an array of strings and not an array of objects:

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

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

You want a result like this

你想要这样的结果

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

To achieve that, try to build up a standard PHP object with those properties and serialize it. Don't serialize a string that contains json.

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

So on the server side, replace your first line of code with this and you'd be good to go:

所以在服务器端,用这个替换你的第一行代码,你可以开始了:

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

#1


0  

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

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

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

Demo

演示

Update:

更新:

Try with -

试一试,

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

#2


1  

The problem is, that you are serializing strings with json_encode, not real PHP classes and properties.

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

This resulting json is an array of strings and not an array of objects:

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

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

You want a result like this

你想要这样的结果

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

To achieve that, try to build up a standard PHP object with those properties and serialize it. Don't serialize a string that contains json.

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

So on the server side, replace your first line of code with this and you'd be good to go:

所以在服务器端,用这个替换你的第一行代码,你可以开始了:

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