PHP, jQuery, SQL and HandleBars



我试图从sql数据库中获取一些数据,并通过AJAX请求将其传递,然后使用Handlebars对其进行模板化。PHP类似于:

<?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请求,所以我真的不知道如何找到错误。

我把php放在html标记之外,它就工作了。

最新更新