WordPress jSON API如何用jquery返回数据?

时间:2011-04-27 19:52:50

标签: json

我在WordPress博客中成功启用了json API,但我很难用jQuery返回数据。

http://example.com/?json=1&count=1&include=title

这是json格式。理想情况下,我想附加一个名为#homeblog的div,这是最后一个帖子标题,链接到帖子本身。

{
  "status": "ok",
  "count": 1,
  "count_total": 1,
  "pages": 1,
  "posts": [
    {
      "id": 1,
      "type": "post",
      "slug": "hello-world",
      "url": "http:\/\/localhost\/wordpress\/?p=1",
      "title": "Hello world!",
      "title_plain": "Hello world!",
      "content": "<p>Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!<\/p>\n",
      "excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!\n",
      "date": "2009-11-11 12:50:19",
      "modified": "2009-11-11 12:50:19",
      "categories": [],
      "tags": [],
      "author": {
        "id": 1,
        "slug": "admin",
        "name": "admin",
        "first_name": "",
        "last_name": "",
        "nickname": "",
        "url": "",
        "description": ""
      },
      "comments": [
        {
          "id": 1,
          "name": "Mr WordPress",
          "url": "http:\/\/wordpress.org\/",
          "date": "2009-11-11 12:50:19",
          "content": "<p>Hi, this is a comment.<br \/>To delete a comment, just log in and view the post's comments. There you will have the option to edit or delete them.<\/p>\n",
          "parent": 0
        }
      ],
      "comment_count": 1,
      "comment_status": "open"
    }
  ]
}

1 个答案:

答案 0 :(得分:2)

如果您想将JSON api返回的一些数据附加到页面,您需要以下内容:

$(document).ready(function(){
    $.getJSON("http://example.com/?json=1&count=1",function(data) {
        $('body').append('<a href="'+data.posts[0].url+'"><div id="homeblog">'+data.posts[0].title+'</div></a>');
    }

我删除了json调用的include=title部分,因为它排除了其他所有内容。您正在使用getJSON返回帖子data,这只是一个构建您的html并append将其添加到某个页面的情况(在我的情况下直接到{{1}标签)

编辑:wordpress问题有wordpress stackexchange。你会有更多的运气在那里问这样的问题。

(添加右括号)