简体   繁体   中英

Split doesn't work with json_encode in JavaScript

I have an array in php like this:

$array_php = (1,2,3,4,5);

In JavaScript I do:

var obj = <?php echo json_encode($array_php); ?>;

If I do alert(obj); I get the content well without problems: 1,2,3,4,5

If I do:

var elem = obj.split(',');

This fail. If I do alert(elem[1]) for example I don't get anything. And the line var elem = ... fails.

If I create the array without json_enconde works fine, but I need access to this object.

What can I do? Thanks!

alert(obj) converts the array to a string. Array-to-string conversion in JavaScript is essentially done with this.join(",") (not exactly, but close enough).

You don't have to do anything to obj to make it an array, it is an array! So just access alert(obj[1]) and you'll get 2 .

That's not a PHP array. Do you mean array(1, 2, 3, 4, 5); ?

Using json_encode like this creates a string with an JavaScript object or array literal, but since you are outputsing it directly into JavaScript, it's not a string, but allready an array in JavaScript. Look at the generated source code. It will be:

var obj = [1, 2, 3, 4, 5];

not

var obj = "[1, 2, 3, 4, 5]";

and also not

var obj = "1, 2, 3, 4, 5";

So you don't need to split it (there is no string to split). Just access the object (or in this case array) directly:

alert(obj[0]); // Shows 1

Hint: Don't use alert() for debuggging. Use console.log() instead and look at the console. There it's easier to see that it's an array and not a string.

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