【问题标题】:multiple returned keys json多个返回键 json
【发布时间】:2015-08-16 03:59:37
【问题描述】:

我有一个运行 k2 的 joomla 站点,并通过在字符串末尾添加 format=json 来从中提取信息:https://www.example.com/posts?format=json 输出如下内容:

{
site: {
      url: "https://www.example.com",
      name: "mySite"
      },
category: {
          id: "67",
          name: "Gauteng",
          alias: "gauteng",
          link: "/tna/provincial/gauteng.html",
          parent: "66",
          extraFieldsGroup: "0",
          image: null,
          ordering: "1",
        events: {
          K2CategoryDisplay: ""
        },
        chidlren: []
       },
items: [{ 
         id="1",
         title="The Title",
         body="body content here..."
        },
        { 
         id="2",
         title="The Title",
         body="body content here..."
        }
}

现在我正在为此创建一个服务,并且只想访问“项目”。

.factory('Posts', function($http) {

  var posts = [];

  return {
        getPosts: function(){
            return $http.get("https://www.example.com/posts?format=json").then(function(response){
                posts = response;
                return posts;
            });
        },
        getPost: function(index){
            return posts[index];
        }
    }

});

它似乎没有工作。有什么方法可以通过调用访问“项目”?

【问题讨论】:

标签: javascript angularjs ionic-framework angularjs-factory angularjs-http


【解决方案1】:

你发帖的语法应该是posts = response.data.items

return $http.get("https://www.example.com/posts?format=json").then(function(response){
    posts = response.data.items; //items here
    return posts;
});

【讨论】:

  • @user2298428 很高兴为您提供帮助..谢谢
  • 效果很好。当它允许我时会接受答案。不幸的是,投票仍然太低
  • 你还需要解析json字符串,不是吗?
  • response.data 属性将是一个 JavaScript 对象或数组,因此对其调用 JSON.parse 将引发异常。我没有投反对票,但请删除对 JSON.parse 的调用,它将引发异常。
  • 很高兴为您服务
猜你喜欢
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
  • 2012-04-18
相关资源
最近更新 更多