【问题标题】:How to return two html contents from ajax?如何从ajax返回两个html内容?
【发布时间】:2015-03-28 12:23:50
【问题描述】:

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

请帮忙...!

【问题讨论】:

  • 无论你在 php 文件中回显什么,你将在成功函数(数据)数据中包含你在 ajax 中回显的值,你可以使用它
  • 您不应该在函数中回显,而是将其添加到变量中并返回。
  • @jeroen 你的意思是为这两个函数声明一个变量而不是返回函数的名称对吗?
  • 不,您应该使用该 html 构建一个字符串并从您的函数中返回,而不是在您的函数中回显 html。请注意,@MarioA 的解决方案也可以,但这是在解决问题而不是解决问题。
  • 你能举一些例子吗?因为如果我只回显只返回一个函数,那么它可以完美运行,但我需要两个,因为我需要刷新两个 html 内容。

标签: javascript php jquery html ajax


【解决方案1】:

您正在回显 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",
   /* ... */
 });

【讨论】:

  • 我尝试了你的代码,但我仍然收到错误警报,是由 AJAX 的条件引起的吗?
  • 您在 ajax 调用中需要 dataType: "json" 而不是 html。如果仍然存在错误,请尝试使用 javascript 控制台进行调试。
  • 哇...谢谢,更改 dataType: "json" 正如你提到的现在完美!非常感谢您的帮助。
猜你喜欢
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2012-07-11
相关资源
最近更新 更多