通过jquery.get()将php数组传递给脚本

时间:2013-12-06 09:16:06

标签: javascript php jquery

在我的剧本中,我有这条线..

$scope.items = [{"id":"1","name":"name 1","description":"description 1","field3":"field3 1","field4":"field4 1","field5 ":"field5 1"}];

我制作了一个data.php文件来模拟上面显示的$ scope.items的数组值

<?php
getaccessories = array("id"=>"1","name"=>"name 1","description"=>"description 1","field3"=>"field3 1","field4"=>"field4 1","field5 "=>"field5 1");

echo json_encode($getaccessories);
?>

我的想法是通过jquery.get()在我的脚本中从data.php接收这个数组到$ scope.items。我尝试了下面的声明没有结果。怎么做?

$scope.items = $.get("data.php", function(data){}, "json");

@sergiu,这是你要求我为data.php做的,请看看我做得对吗?

<?php

// $getaccessories = array("id"=>"1","name"=>"name 1","description"=>"description 1","field3"=>"field3 1","field4"=>"field4 1","field5 "=>"field5 1");

$getaccessories = array();
$accessory = new stdClass();
$accessory->id = "1";
$accessory->name = "name 1";
$accessory->description = "description 1";
$accessory->field3 = "field3 1";
$accessory->field4 = "field4 1";
$accessory->field5 = "field5 1";

$getaccessories[] = $accessory;


echo json_encode($getaccessories);
?>

------为Sergiu编辑------

这是chrome的console.log的输出,原始值为$ scope.items

[Object]
0: Object
        age: 50
        name: "Moroni"
  __proto__: Object
  length: 1
__proto__: Array[0]

这里是带有$ .get()

的$ scope.items
Object {readyState: 1, setRequestHeader: function, getAllResponseHeaders: function, getResponseHeader: function, overrideMimeType: function…}
    $$v: Array[1]
        0: Object
            age: 50
            name: "Moroni"
        __proto__: Object
        length: 1
        __proto__: Array[0]

我希望这会有所帮助

1 个答案:

答案 0 :(得分:2)

您可能需要

$.get("data.php", function(data){
    $scope.items = data;
}, "json");

$ .get的第二个参数是回调函数,就像在收到我从服务器请求的数据时回调给我的那样。

我也猜测你$前面有getaccessories

您期待一组对象。 您可以像这样构建它:

$getaccessories = array();
$accessory = new stdClass();
$accessory->id = "1";
$accessory->name = ="name 1";
...

$getaccessories[] = $accessory;