如何通过Ajax请求格式化角度范围的PHP Json数组

时间:2018-01-08 06:06:59

标签: javascript php mysql angularjs ajax

所以我试图避免php while循环从Mysql中获取数据并使用html标签打印出我的ajax查询结果。它使得我的Ajax查询无所谓。

我想到的第一件事就是将MySQL结果数组直接发送回可以更新Angular范围的javascript。所以所有的html都已经在客户端,而agular会根据收到的数据重复它。

我将从我认为在我的代码中工作的东西开始,但是evry会在之后添加;

在PHP中;

$data = array();
$data[0] = 'OK';  // status from server OK/ERROR
$data[1] = '{id: 1, name: "a name", cote: "10.5", style: "jungle", centre: "supercentre", img: "x"},
{id: 2, name: "ma nouvelle route angulaire2", cote: "10.5", style: "jungle", centre: "supercentre", img: "x"},
{id: 3, name: "ma nouvelle route angulaire3", cote: "10.5", style: "jungle", centre: "supercentre", img: "x"}';  


header("content-type:application/json");
echo json_encode($data);

现在我只想弄明白,但最终我的目标是将Mysql结果传递给数据[1];

之后回到javascript更新角度范围。请注意,这部分代码不在主角应用程序中,而是在我的javascript promise函数中处理所有ajax请求。

   var scope = angular.element($("#object_container")).scope();
        scope.$apply(function(){
        scope.objects = data[1];
    });

我可以在控制台中看到数据[1]的内容。但是范围没有显示它。我认为Angular并不喜欢我编写阵列的方式。

我也试过

$data = array();
$data[0] = 'OK';  // status from server OK/ERROR
$data[1][0] = '{id: 1, name: "ma nouvelle route angulaire1", cote: "10.5", style: "jungle", centre: "supercentre", img: "x"}';
$data[1][1] = '{id: 2, name: "ma nouvelle route angulaire2", cote: "10.5", style: "jungle", centre: "supercentre", img: "x"}';
$data[1][2] = '{id: 3, name: "ma nouvelle route angulaire3", cote: "10.5", style: "jungle", centre: "supercentre", img: "x"}';  


header("content-type:application/json");
echo json_encode($data);

控制台;

这是来自php的整个数据数组

(2) ["OK", Array(3)]    

The scope before update

ajax-process.js:71 (3) [{…}, {…}, {…}]   


And the scope after update

ajax-process.js:73 (3) ["{id: 1, name: "ma nouvelle route angulaire1", cote…style: "jungle", centre: "supercentre", img: "x"}", "{id: 2, name: "ma nouvelle route angulaire2", cote…style: "jungle", centre: "supercentre", img: "x"}", "{id: 3, name: "ma nouvelle route angulaire3", cote…style: "jungle", centre: "supercentre", img: "x"}"]

更新 这给了我正确的输出,但我的页面没有使用新的范围值更新。

$data = array();
$data[0] = "OK";  // status from server OK/ERROR
$data[1][0]->id = "1";
$data[1][0]->name = "route Angulaire";
$data[1][0]->cote = "10.5";
$data[1][0]->style = "jungle";
$data[1][0]->centre = "some center";

0 个答案:

没有答案