php到js数组转换为jquery的ajax

时间:2011-03-03 23:55:53

标签: php javascript jquery ajax json

我试图将5个PHP数组转换为5个js数组。

我过去常常用json将php变量传递给js变量:

$return['variable'] = $variable;
echo json_encode($return);

然后在js端将其作为json对象获取,如下所示:

success : function(data) {

    alert(data.variable);

}

现在情况有点复杂,我需要将这5个php数组从php脚本转移到我的js脚本中作为5个js数组:

PHP数组:

$i = 0;
while ($location = mysql_fetch_array($get_locations)) {

    $location_full_name[$i] = $location['loc_full_name'];
    $location_main_name[$i] = $location['loc_main_name'];
    $location_sub_name[$i] = $location['loc_sub_name'];
    $location_anchor_id[$i] = $location['loc_anchor_id'];
    $location_type[$i] = $location['loc_type'];

    $i++;
}

并填写这些相应的数组:

var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();

我不知道该怎么做。希望我能得到一些帮助:)

的问候, 亚历山大

3 个答案:

答案 0 :(得分:2)

也许如果你在“数据”中发布什么回报,那么我们可以帮助你更多(我认为)。和合。

我建议,对于你的php代码,你将数据设置到数组中:

$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
    $rsl[$i]['full_name'] = $location['loc_full_name'];
    $rsl[$i]['main_name'] = $location['loc_main_name'];
    $rsl[$i]['sub_name'] = $location['loc_sub_name'];
    $rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
    $rsl[$i]['type'] = $location['loc_type'];
    $i++;
}
echo json_encode($rsl);

所以要在javascript上搞定这个

// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
     $.each(data, function(index, arr){
          location_full_name[index] = arr['full_name'];
          ...
     });
}

答案 1 :(得分:0)

对于每个数组,存储从json_encode返回的值。和/或使它们成为一个数组/对象并执行相同的操作。

答案 2 :(得分:0)

您可以使用实际上是有序地图的PHP数组。以下是一个例子:

PHP:

<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>

JavaScript(jQuery):

<script type="text/javascript">
$(function() {
    $.get("test.php", function(data) {
        console.log(data.full_name[1]); // Prints "Siku-Siku.com".
    }, "json");
});
</script>