2013-08-21 17 views
1

我想從一個sql數據庫中取出一些數據並通過一個AJAX請求傳遞給它,然後用Handlebars對它進行模板化。 的PHP是這樣的:PHP,jQuery,SQL和HandleBars

<?php 

function isXHR() { 
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']); 
} 


function connect(){ 
    global $pdo; 
    $pdo = new PDO("mysql:host=localhost;dbname=personal", "root", ""); 
} 

function get_photos() { 
    global $pdo; 

    $stmt = $pdo->prepare(' 
     SELECT url, name, smt 
     FROM photos 
     LIMIT 50'); 
    $stmt->execute(); 

    return $stmt->fetchAll(PDO::FETCH_OBJ); 
} 

頁索引是這樣的:

<?php 
    require 'functions.php'; 
    connect(); 

    if (isXHR()) 
    { 
     echo json_encode(get_photos()); 

     return; 
    } 
?> 

<ul class="photos_list"> 

    <script id="photo_list_template" type="text/x-handlebars-template"> 
     {{#each this}} 
     <li data-smt="{{smt}}"> 
      <img src="{{url}}" alt="{{name}}"/> 
     </li> 
     {{/each}} 
    </script> 
</ul> 

而jQuery是這樣的:

var photos = { 
    init: function(config) { 
     this.config = config; 

     this.setupTemplates(); 
     this.fetchphotos(); 

     $.ajaxSetup({ 
      url: 'index.php', 
      type: 'POST' 
     }); 


    }, 


    setupTemplates: function() { 
     this.config.photoListTemplate = Handlebars.compile(this.config.photoListTemplate); 

    }, 

    fetchphotos: function() { 
     var self = photos; 

     $.ajax({ 

      dataType: 'json', 
      success: function(results) { 

       console.log(results); 
       self.config.photosList.empty(); 

       if (results[0]) { 
        self.config.photosList.append(self.config.photoListTemplate(results)); 
       } else { 
        self.config.photosList.append('<li>Nothing returned.</li>'); 
       } 
      } 
     }); 

    } 
}; 

photos.init({ 
    photoListTemplate: $('#photo_list_template').html(), 
    photosList: $('ul.photos_list') 
}); 

我不知道如何使它工作,但我知道我做錯了什麼。這是我第一次使用PHP和ajax請求,所以我不知道如何找到這個錯誤。

+1

錯誤是什麼? –

+0

沒有錯誤,只是沒有抓住任何東西,但我解決了它。 –

回答

2

我把php放在html標籤之外,它工作。