iT邦幫忙

0

PHP-單獨開啟商品清單使用handlebars顯示到HTML筆記記錄

index.php

<div id="commodity-list"> 
     <div class="close">x</div>
        <div class="container">
        <!-- 此為商品清單Template -->
        
         </div>  
    </div>
</div>

<!-- 商品清單Template部分 -->
<script id="commodity-list-item-template" type="text/x-handlebars-template">
  <img src="{{img}}" alt="{{img}}">
    <div class="content">
      <div class="book-name">{{book_name}}</div>
      <div class="author">作者:<span>{{author}}</span></div>
      <div class="Publishing-house">出版社:<span>{{Publishing_house}}</span></div>
      <div class="Publication-date">出版日期:<span>{{Publication_date}}</span></div>
      <div class="price">NT${{price}}</div>
      <div class="button" data-id="{{id}}">加入購物車</div>
    </div>
</script>

action.js

  var panel={
    el: '#panel',
  };
  var commodity_list_template = $('#commodity-list-item-template').html();
  var commodity_list_template_compile = Handlebars.compile(commodity_list_template);
  
  $(panel.el)
      .on('click', '#commodity li', function(e) {//開啟商品書單清單
        e.preventDefault();
        var id = $(this).data('id');
        $(commodity_list.el).addClass('open');
        $.post("commodity_list.php", {id:id},
          function (data, textStatus, jqXHR) {
            $(commodity_list.el).find('.container').html('');             $(commodity_list.el).find('.container').append(commodity_list_template_compile(data)); 
        });
    })

commodity_list.php

<?php
header('Content-Type: application/json; charset=utf-8');
include('../../../db.php');

try {
	$pdo = new PDO("mysql:host=$db[host];dbname=$db[dbname];port=$db[port];charset=$db[charset]", $db['username'], $db['password']);
} catch (PDOException $e) {
	echo "Database connection failed.";
	exit;
}
$sql = 'SELECT id, book_name,author, Publishing_house, Publication_date, price, img FROM commodity WHERE id=:id';
$statement = $pdo->prepare($sql);
$statement->bindValue(':id', $_POST['id'], PDO::PARAM_INT);
$result = $statement->execute();
$commodity = $statement->fetch(PDO::FETCH_ASSOC);

if($result){
    echo json_encode(['id'=>$commodity['id'], 'book_name'=> $commodity['book_name'], 'author'=> $commodity['author'],'Publishing_house'=> $commodity['Publishing_house']
    ,'Publishing_date'=> $commodity['Publishing_date'],'price'=> $commodity['price'],'img'=> $commodity['img']]);
}
?>

尚未有邦友留言

立即登入留言