简体   繁体   English

如何从jquery读取Json_encoded php数组?

[英]How to read Json_encoded php array from jquery?

I have a php array like this one : 我有一个像这样的php数组:

Array
(
    [0] => banana, peach, cherry
    [1] => strawberry, apple, lime
)

I pass it to Jquery using json_encode($myArray) 我使用json_encode($ myArray)将其传递给Jquery

In Jquery I receive my array like this : ["banana, peach, cherry","strawberry, apple, lime"] 在Jquery中,我收到这样的数组:[“香蕉,桃子,樱桃”,“草莓,苹果,酸橙”]

Now I wanna extract each value : "banana, peach, cherry" & "strawberry, apple, lime" 现在我想提取每个值:“香蕉,桃子,樱桃”和“草莓,苹果,酸橙”

When I try to use this : 当我尝试使用此:

$.each(data, function(key, value){
    alert(value);
});

it alerts me each chars : [ " bana n................ etc instead each value. 它会提醒我每个字符:[“ bana n ................等,而不是每个值。

Do you know why ? 你知道为什么吗 ?

EDIT : 编辑:

This is how I receive my data from php : 这就是我从php接收数据的方式:

$.post('ajax/fruits.php', function(data) {
    var obj = $.parseJSON(data);
    var chunks = obj['chunks'] // gives me : ["banana, peach, cherry","strawberry, apple, lime"]
    if (obj['error']==0) {
        mix_fruits(chunks); // a function that should extract each value
    }
});

You don't show how you are passing and receiving the data , but somewhere in the process you are making a mistake. 您没有显示如何传递和接收data ,但是在过程中的某个地方您犯了一个错误。

It is evident from the description that data is a string, not an array as it should have been based on the PHP variable. 从描述中可以明显看出, data是字符串,而不是数组,因为它本应基于PHP变量。 And since the string begins with the characters that make up the JSON representation of your data, this means the JSON is being wrapped into a string instead of parsed as a JavaScript literal. 并且由于字符串以构成数据的JSON表示的字符开头,因此这意味着JSON被包装为字符串,而不是解析为JavaScript文字。

Assuming that passing/receiving is not done through an AJAX request (in which case jQuery would almost certainly parse the data automatically) I 'm guessing that you are doing this: 假设没有通过AJAX请求完成传递/接收(在这种情况下jQuery几乎肯定会自动解析数据),我猜测您正在这样做:

var data = '<?php echo json_encode($data); ?>';

while you should instead be doing this: 而您应该这样做:

var data = <?php echo json_encode($data); ?>; // no quotes!

You need to parse the JSON object before you can use it, 您需要先解析JSON对象,然后才能使用它,

var jsonObj = jQuery.parseJSON(data);

then to loop through each item use this, 然后遍历每个项目使用这个,

for(var key in jsonObj)
{
    curr = jsonObj[key];
}

And if you want to use non-jquery one, 而且,如果您要使用非jQuery之一,

Parse JSON in JavaScript? 在JavaScript中解析JSON?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM