[英]converting with json_encode()
<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = '<?php echo json_encode($array); ?>';
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I have PHP array with two elements, when I converting this array to javascript array with json_encode()
javascript divide my PHP array into set of chars, so in javascript array in a result i have a lot of elements. 我有两个元素的PHP数组,当我用json_encode()
将这个数组转换为javascript数组时javascript将我的PHP数组分成一组字符,所以在javascript数组中我有很多元素。 How to convert PHP array with two elements to javascript array with the same two elements? 如何将具有两个元素的PHP数组转换为具有相同两个元素的javascript数组?
You php function json_encode will give you a valid object, that's in fact what it means, J ava S cript O bject N otation. 你的php函数json_encode将为你提供一个有效的对象,这实际上意味着什么, J ava S cript O bject N otation。
So by using it as it is you will create an object in your JavaScript code. 因此,通过使用它,您将在JavaScript代码中创建一个对象。 By enclosing it between apostrophes you are making it a string (who's value can be parsed as JSON). 通过将它放在撇号之间,你将它变成一个字符串(谁的值可以解析为JSON)。
So the simplest change would be to remove the apostrophes. 所以最简单的改变就是删除撇号。 So this line: 所以这一行:
var js_array = '<?php echo json_encode($array); ?>';
Should become 应该成为
var js_array = <?php echo json_encode($array); ?>;
Replace you code with the following code.. 用以下代码替换代码..
<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = <?php echo json_encode($array); ?>;
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I hope its help you..... 我希望它对你有所帮助.....
The problem is that you have enclosed the json_encode in colons so you are converting it to a string. 问题是您已将json_encode括在冒号中,因此您将其转换为字符串。 The javascript it produces is like this: 它产生的javascript是这样的:
var js_array = '["first elem","second elem"]';
Here js_array
is an string but you want an array. 这里js_array
是一个字符串,但你想要一个数组。 What you have to do is to produce the json directly as it will yield an array: 你要做的是直接生成json,因为它会生成一个数组:
var js_array = <?php echo json_encode($array); ?>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.