简体   繁体   中英

How to read Json_encoded php array from jquery?

I have a php array like this one :

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

I pass it to Jquery using json_encode($myArray)

In Jquery I receive my array like this : ["banana, peach, cherry","strawberry, apple, lime"]

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.

Do you know why ?

EDIT :

This is how I receive my data from 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.

It is evident from the description that data is a string, not an array as it should have been based on the PHP variable. 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.

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:

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,

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,

Parse JSON in JavaScript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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