js中的JSON设置for循环中的值

时间:2014-07-03 06:02:18

标签: javascript json

我有PHP代码,可以从数据库中选择值。

此代码正在运行。

$query = "select * from  tblUser where tag=1 and UserName='something'";

$result= mysql_query($query);
$ncrsForm[] = array();
$address[] = array();
$commDate[] = array();
$prosDate[] = array();
$x=0;
while($rows=mysql_fetch_array($result))
{
    $lat[$x]=$rows['X'];
    $lng[$x]=$rows['Y'];
    $ncrsForm[$x]=$rows['NCRSFormNo'];

    $address[$x] =$rows['PlaceNo'] . " " . $rows['PlaceStreet'] . " " . $rows['PlaceBlock'] . " " . $rows['PlaceLot'] . " " .
    $rows['PlaceSubdivision'] . " " . $rows['PlaceLandmark'] . " " . $rows['PlaceBarangay'] . " " . $rows['PlaceTown'];
    $commDate[$x] = $rows['CommDate'];
    $prosDate[$x] = $rows['ProsDate'];
$x++;

}   

之后我在JS中调用PHP变量:

ncrsForm =<?php echo json_encode($ncrsForm); ?>;
address =<?php echo json_encode($address); ?>;
commDate =<?php echo json_encode($commDate); ?>;
prosDate =<?php echo json_encode($prosDate); ?>;

上面的代码正在运行。它显示数据库中的值,但下面的代码不起作用。代码markers.push后执行停止。我不知道代码中有什么问题..

var markers[];
for (var i=0; i<address.length; i++)
{

    markers.push({
        name: "marker"+(i+1),
        ncrsForm: ncrsForm[i],
        adds: address[i],
        com: commDate[i],
        pros: prosDate[i]
        });
}
var jsOnmarkers = JSON.stringify(markers);

1 个答案:

答案 0 :(得分:0)

我可以看到数组声明是代码中的一个问题。

数组声明。它应该是

var markers = [];

下面的示例代码工作正常。试试吧。

var markers = [];
markers.push({name:'xyz', address:'abc'});
var jsonmarks = JSON.stringify(markers);
jsonmarks; // Output : "[{"name":"xyz","address":"abc"}]"