将一些JSON数据移动到唯一的Div中

时间:2014-11-30 22:21:09

标签: javascript jquery json

我有一个blogger.com博客,我已经设法创建了一个从博客中获取数据的脚本 - 我不太擅长js / json,所以我对此有点盲目; - )

我喜欢2 DIVS中的输出,这些输出对于帖子ID和内容是唯一的:

这是剧本:

<html>
  <head>
    <title>Test</title>
  </head>
  <body>

<script type="text/javascript">
    function posts(json) {
      // Get five recent posts
      for (var i = 0; i < 2; i++)
      {
        var posturl;  
        // Get rel=alternate for truly post url
        for (var j=0; j < json.feed.entry[i].link.length; j++)
        {
          if (json.feed.entry[i].link[j].rel == 'alternate')
          {
            posturl = json.feed.entry[i].link[j].href;
            break;
          }
        }
        // if the Blogger-feed is set to FULL, then the content is in the content-field
        // if the Blogger-feed is set to SHORT, then the content is in the summary-field
        if ("content" in json.feed.entry[i]) {
          var postcontent = json.feed.entry[i].content.$t;}
        else
        if ("summary" in json.feed.entry[i]) {
          var postcontent = json.feed.entry[i].summary.$t;}
        else var postcontent = "";
        // strip off all html-tags
        var re = /<\S[^>]*>/g; 
        postcontent = postcontent.replace(re, "");
        // reduce postcontent to 200 characters
        if (postcontent.length > 200) postcontent = postcontent.substring(0,200);
        // Get posts title
        document.write("Post Id = "+json.feed.entry[i].id.$t);
        document.write('<br/>');
        document.write("Post content = "+postcontent);
        document.write('<br/><br/>');
      }
        }    
</script>

<script src="http://ironheartuk123.blogspot.com/feeds/posts/default?alt=json-in-script&callback=posts"></script>

  </body>
</html>

当我将页面加载到浏览器中时,我在屏幕上显示:

Post Id = tag:blogger.com,1999:blog-5655651846573938667.post-5882120439717312684
Post content = Test post 2

Post Id = tag:blogger.com,1999:blog-5655651846573938667.post-8794205203420774123
Post content = Test post 1

这就是我更喜欢的输出!

<div id="5882120439717312684">Test post 2</div>

<div id="8794205203420774123">Test post 1</div>

完成该步骤后,我将能够将Div移动到页面上的正确位置。我认为这很容易; - )

任何帮助都非常感谢!!

1 个答案:

答案 0 :(得分:0)

使用jQuery:

var re = /post-\d+/;
var postId = re.exec(json.feed.entry[i].id.$t);
$("#" + postId[0]).html(postcontent);