2013-12-19 39 views
0

我正在檢索從谷歌的API的一些信息,並且將它們放置在一個單一的變量,然後把它們插入到一個div的DOM像這樣:在PHP頁面上顯示JS的另一種方法?

$(function() { 
    // Load the info via Google's API 
    $.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641/activities/public?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) { 

     // Variable to hold the HTML we'll generate 
     var html = ''; 
     // how many posts we're displaying on the page 
     var numberOfPosts = 3; 

     // Loop over the results, generating the HTML for each <li> item 
     for (var i=0; i<numberOfPosts; i++) { 
      html += '<article>'; 
      html += '<img src="'+data.items[i].actor.image.url+'">'; 
      html += '<p>'+data.items[i].title+'</p>'; 
      html += '<p>'+data.items[i].published+'</p>'; 
      html += '</article>'; 
     } 

     // Insert the generated HTML to the DOM 
     $('.google-posts-container').html(html); 
    }); 
}); 

我的問題是:有沒有存儲每一塊的方式在每個自己的變量中包含信息,然後通過回顯變量來分別獲取信息?所以我不必硬編碼所有的HTML。

+0

你的意思是你想用佔位符,而不是連接使用JavaScript的HTML字符串的HTML模板? – galchen

+0

是的,類似的東西。 – RicoRos

+0

不知道這與PHP有什麼關係......如果你的意思是模板是在PHP中,你可以檢索模板,然後爲每個職位使用模板來爲每個職位生成一篇文章。 –

回答

1

在天回我會做:

<div id="google-posts-container"> 
    <article> 
     <img src="{{image}}"> 
     <p>{{title}}</p> 
     <p>{{published}}</p> 
    </article> 
</div> 

<script type="text/javascript"> 
// render a template (replace variables and return html) 
function renderTemplate(tmpl, data){ 
    for (k in data){ 
     while(tmpl.indexOf('{{'+k+'}}') > -1){ 
      tmpl = tmpl.replace('{{'+k+'}}', data[k]); 
     } 
    } 
    return tmpl; 
} 
$(function(){ 
    // our template 
    var template = $('#google-posts-container').html(); 
    $('#google-posts-container').html(''); // or clear() 

    $.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641" 
     +"/activities/public" 
     +"?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) { 
     // Variable to hold the HTML we'll generate 
     var html = ''; 
     // how many posts we're displaying on the page 
     var numberOfPosts = 3; 

     // Loop over the results, generating the HTML for each <li> item 
     for (var i=0; i<numberOfPosts; i++) { 
      html += renderTemplate(template, { 
       image : data.items[i].actor.image.url, 
       title : data.items[i].title, 
       publish : data.items[i].published 
      }); 
     } 

     // Insert the generated HTML to the DOM 
     $('.google-posts-container').html(html); 
    }); 

}); 
</script> 

現在我用angularjs

+0

您應該可以解釋一下,這叫做「微模板」,可以讓OP在良好的Google搜索中取得領先。 +1,因爲這是最簡單的解決方案,不包括另一個單片庫。 – srquinn

0

關於通過 'galchen' 的評論 - 不要使用嚴重&(或)大項目angular.js。只要看看源代碼。 (不能添加子評論,這就是爲什麼我寫到主分支)