gpt4 book ai didi

javascript - 如何从ajax返回两个html内容?

转载 作者:行者123 更新时间:2023-12-02 16:18:50 26 4
gpt4 key购买 nike

我正在用 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&amp;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() 返回,但我没有运气

请帮忙...!

最佳答案

您正在回显 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_startob_get_clean 您可以将回显从标准输出缓冲区重定向到变量。这样你就可以将变量内容放入你的json数据中。

此外,使用 json-data 作为响应,您需要在 ajax 调用中使用 dataType: 'json':

 $.ajax({
/* ... */
dataType: "json",
/* ... */
});

关于javascript - 如何从ajax返回两个html内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29317100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com