2

嗨,我在将值从 php 数组添加到 javascript 对象时遇到问题到目前为止我在数组中有一个 php 值

$data=array(5,10,15,20);

我将其转换为 json 以准备 javascript

$js_array = json_encode($data);

这是javascipt部分

数据 :<?php echo json_encode( $data ); ?>

我认为它正在阅读它

data : [5] or data : [5101520]

应该把它读作

data : [5,10,15,20]

谢谢大家希望你能帮助我

这是php数组存储

<?php  
$data = array();

$que = "SELECT name FROM table1 ORDER BY date ASC";

$res = mysql_query($que, $con);

if(mysql_num_rows($res)>0){

while($row = mysql_fetch_array($res)){

$data[] = $row['name'];

}}

$js_array = json_encode($data);

?>'

这里是 var dump data echo array(4) { [0]=> string(1) "5" 1 => string(2) "10" [2]=> string(2) "20" [3]= > 字符串(2)“15” }

这是当前输出

4

2 回答 2

3

php

// array
$data = array(1,2,3,4,5);
// array -> json
$json = json_encode($data);
// print json
echo $json;

带有 jquery 的 js:

$.getJSON( "script.php", function( data ) {
console.log(data)
}
于 2013-10-16T16:42:29.580 回答
0

您定义 php 数组的方式将引发语法错误。

像这样使用:

<?php
$data=array(5,10,15,20);
print_r(json_encode($data));
?>

它会给你输出:

data : [5,10,15,20]

这是演示: http ://codepad.org/UVFT6m67

现在您可以将此 json 对象与您的 javascript 一起使用。

于 2013-10-16T16:49:45.577 回答