【问题标题】:angularjs ajax with PHP variable带有PHP变量的angularjs ajax
【发布时间】:2014-06-10 11:18:57
【问题描述】:

我在 angularjs 中有一个循环 ajax json 响应的代码,如下所示:

<div ng-repeat="post in posts">
{{post.title}}
{{post.url}}
</div>

它工作正常。如何根据 json 传递 PHP 变量?

假设 json 看起来有这样的结构:

post
    my_slug
    my_title
post
    my_slug2
    my_title2

我有一个这样的 PHP 数组:

my_slug
    url
my_slug2
    url2
PHP 中的

my_slug 匹配 json 中的 my_slug。

Ajax 调用

var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
    $http.get('<?php echo u(); ?>test/json.txt').
    success(function(data, status, headers, config) {
        $scope.posts = data;
    }).
    error(function(data, status, headers, config) {
    });
});

结果应该是这样的:

<div>
    my_title
    url
</div>
<div>
    my_title2
    url2
</div>

在 angularjs json 循环中,我想从我的 PHP 数组中获取 url 和 url2。如何?我可以通过我的 Ajax 响应传递 PHP 数组吗?

【问题讨论】:

  • 你的问题不清楚!让它更具体。
  • 我还添加了一个“结果”,说明从 ajax json 和 PHP 数组循环时的样子。
  • 你把我弄丢了 Jens,如果你使用 $http.get 调用 PHP 脚本并且它确实返回了格式良好的 JSON,那么如何在 ng-repeat 中使用它就很简单了。请进一步说明您想要实现的目标是什么
  • 显示实际变量的真实样子,从您的缩进来看,不清楚它是键还是值。

标签: javascript php ajax json angularjs


【解决方案1】:

将您的 php 数据分配给一个变量,然后循环遍历数据以在分配之前对其进行操作。

 $scope.postsPhp = [{$postsJSON}]; /// I usually make the php arrays json

 success(function(data, status, headers, config) { for (var i = 0; i <
 data.length; i++) { 
   data[i].title = data[i].url + ' ' + $scope.postsPhp[i].url; }   

$scope.posts = 数据; });

【讨论】:

  • 他不必加入这两个字符串来显示它们,他已经在 html 中有 {{post.url}}
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2011-04-25
  • 2014-11-18
  • 2011-10-09
  • 1970-01-01
相关资源
最近更新 更多