我正在开发一个PHP的购物车应用程序,我有两个功能,第一个功能是显示购物车中的总项目,第二个功能列表购物车中的所有产品。
如何从AJAX返回这两个函数的html输出?
这是php服务器端:
<?php
require '../init.php';
require $ROOT . '/functions/basic.php';
require $ROOT . '/functions/products.php';
if(isset($_REQUEST['id']))
{
$product_id = $_REQUEST['id'];
$_SESSION['cart'][$product_id] = isset($_SESSION['cart'][$product_id]) ? $_SESSION['cart'][$product_id] : "";
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
$qty = dbRow("SELECT id, quantity FROM products WHERE id = $product_id");
$quantity = $qty['quantity'];
if($_SESSION['cart'][$product_id] < $quantity)
{
$_SESSION['cart'][$product_id] += 1; //add one to the quantity of the product with id $product_id
}
}
function writeCartTotal()
{
echo '
<div class="col-md-4">
<a href="carts"><h1><span class="glyphicon glyphicon-shopping-cart"></span>
';
if(isset($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
}
else{
echo "0";
}
echo '
items
</h1></a>
</div>
<div class="col-md-4">
<h1>
';
if(!empty($_SESSION['cart'])) { //if the cart isn't empty
$total = "";
$total_score = "";
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = dbQuery("SELECT product_title, product_description, price, product_score FROM products WHERE id = " . $product_id);
$count = $sql->rowCount();
//Only display the row if there is a product (though there should always be as we have already checked)
if($count > 0) {
list($name, $description, $price, $score) = $sql->fetch(PDO::FETCH_NUM);
$line_cost = $price * $quantity; //work out the line cost
$line_score = $score * $quantity;
$total = $total + $line_cost; //add to the total cost
$total_score = $total_score + $line_score;
}
}
//show the total
echo '<span class="label label-success">'. number_format($total) . " <span> ₭</span></span>";
echo '
</h1>
</div>
<div class="col-md-4">
<h1>
';
echo '<span class="label label-success">'. number_format($total_score) . " <span > PG</span></span>";
}else{
//otherwise tell the user they have no items in their cart
echo "0";
}
echo '
</h1>
</div>
';
}
function writeCartSummary()
{
echo '<h1>Welcome to Your Cart</h1>';
if(!empty($_SESSION['cart'])) { //if the cart isn't empty
$total = "";
$total_score = "";
//show the cart
echo "<table class=\"table table-hovered table-bordered\" border=\"1\" padding=\"3\" width=\"40%\">"; //format the cart using a HTML table
echo '<tr>
<th align="center">Product Name</th>
<th align="center">Quantity</th>
<th align="center">Price</th>
<th align="center">Score</th>
<th align="center">Delete</th>
</tr>';
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = dbQuery("SELECT product_title, product_description, price, product_score FROM products WHERE id = " . $product_id);
$count = $sql->rowCount();
//Only display the row if there is a product (though there should always be as we have already checked)
if($count > 0) {
list($name, $description, $price, $score) = $sql->fetch(PDO::FETCH_NUM);
$line_cost = $price * $quantity; //work out the line cost
$line_score = $score * $quantity;
$total = $total + $line_cost; //add to the total cost
$total_score = $total_score + $line_score;
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$name</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity</td>";
echo "<td align=\"center\"><h4>". number_format($line_cost) . " <span class='label label-success'> ₭</span></h4></td>";
echo "<td align=\"center\"><h4>". number_format($line_score) . " <span class='label label-success'> PG</span></h4></td>";
echo '<td><a href="?action=delete&id='.$product_id.'" class="btn btn-danger btn-sm">Delete</a>';
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\"><h1>Total</h1></td>";
echo "<td align=\"right\"><h1>". number_format($total) . " <span class='label label-success'> ₭</span></h1></td>";
echo "<td align=\"right\"><h1>". number_format($total_score) . " <span class='label label-success'> PG</span></h1></td>";
echo "</tr>";
//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "<div class='well'><h3>You have no items in your shopping cart.</h3></div>";
}
}
$value = array("response"=>"OK","totals"=>writeCartTotal(), "summaries"=>writeCartSummary());
echo json_encode($value);
?>
这是AJAX调用方法:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$(document).ready(function(){
$("a.add_to_cart").click(function(){
var id = $(this).attr('id');
var productname = $(".product_name_page").attr('id');
if(isNumber(id))
{
//alert("OK");
$.ajax({
type: "GET",
url: "ajax/ajaxAddToCart.php",
data: "id=" + id,
dataType: "html",
cache: false,
success: function(data){
if(data.response == "OK")
{
swal("Success!", productname, "success");
$("#load_item_total").html(data.totals);
$("#navbar_shopping_cart").html(data.summaries);
}
else
{
$.alert({
title: '<h3 style="color: red;">Error!</h3>',
content: "<span class=''>There is an error, please try again!</span>",
confirm: function(){
}
});
}
}
});
}
});
});
我的问题是如何从AJAX返回这两个html内容函数?
我使用json_encode()返回,但我没有运气
请帮忙......!
答案 0 :(得分:2)
您正在回显html而不是将其存储在字符串中。要解决这个问题,最快的方法是将echo输出重定向到php变量:
ob_start();
writeCartSummary();
$cartSummary = ob_get_clean();
ob_start();
writeCartTotal();
$cartTotal = ob_get_clean();
$value = array("response"=>"OK","totals"=>$cartTotal , "summaries"=>$cartSummary );
echo json_encode($value);
使用ob_start
和ob_get_clean
,您可以将回显从标准输出缓冲区重定向到变量。您可以将变量内容放入json数据中。
此外,以json-data作为响应,您需要在ajax调用中使用dataType: 'json'
:
$.ajax({
/* ... */
dataType: "json",
/* ... */
});