【问题标题】:return json data from php for emberjs in the right format with $.getJSON使用 $.getJSON 以正确的格式从 php 为 emberjs 返回 json 数据
【发布时间】:2013-11-16 10:47:35
【问题描述】:

我看了这个tutorial

并尝试创建自己的 php 端脚本来生成 json 数据。

但是,我未能创建多级数组。

在示例中,

的json结果
{
  "nextId": null,
  "items": [{
          "title": "Docker, the Linux container runtime: now open-source",
          "url": "http://docker.io",
          "id": 5445387,
          "commentCount": 39,
          "points": 146,
          "postedAgo": "2 hours ago",
          "postedBy": "shykes"
      }, {
          "title": "What\u0027s Actually Wrong with Yahoo\u0027s Purchase of Summly",
          "url": "http://hackingdistributed.com/2013/03/26/summly/",
          "id": 5445159,
          "commentCount": 99,
          "points": 133,
          "postedAgo": "2 hours ago",
          "postedBy": "hoonose"
      },
  ],
  "version": "1.0",
  "cachedOnUTC": "\/Date(1364333188244)\/"
}

生成后,我可以使用$resultJSON= json_encode($resultArray); 生成内部级别,即title、url、id 等,但不是'items' 对象。我想知道,items 对象是来自表名还是通过对数组中生成的数组数据进行编码而创建的? 我使用这个 php 文件中编码为 json 的数据:

$query = "SELECT user_id, username, legacy_id, date_created
FROM eq_user";
$result = mysqli_query($connection, $query);
$numRows = mysqli_num_rows($result);
$resultArray = mysqli_fetch_assoc($result);
$resultJSON= json_encode($resultArray);
echo $resultJSON;

emberjs 应用会是这样的

App.Item.reopenClass({
  all: function() {
      return $.getJSON("/get_data.php").then(function(response) {
        var items = [];                     
        response.items.forEach( function (item) {
          items.push( App.Item.create(item) );
        });

          return items;
      });
  }
});

注意:项目是我认为的对象,但我不知道如何在 php 中正确生成它作为多级数组的 json 数据。

另外,还有一个问题,我应该使用 json_encode 还是不使用?因为我看到教程提到 Emberjs 使用 jsonp ......它是一种特殊的格式吗?我应该如何在 PHP 中处理这个 jsonp?

谢谢!

【问题讨论】:

    标签: jquery ajax json ember.js jsonp


    【解决方案1】:

    你可以这样做

     $resultArray = array();
     while ($row = mysqli_fetch_assoc($result)) {
        $resultArray[] = $row;
     }
    
     $resultJSON= json_encode(array("items"=>$resultArray));
    

    祝你好运

    【讨论】:

    • en.wikipedia.org/wiki/JSONP 是一种用于从不同域的服务器请求数据的技术
    • 谢谢!顺便说一句,如何返回该表中的所有记录?我尝试了其他几种方法,但永远无法想到使用 json 的正确方法,因为目前 mysqli_fetch_assoc($result);只能生成一条记录,甚至无法确定生成哪条记录。
    • 绝妙的解决方案!非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2014-04-29
    • 2011-06-11
    • 2016-07-19
    相关资源
    最近更新 更多