dongping8572 2015-03-28 12:23
浏览 110
已采纳

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

I'm developing a shopping cart application in PHP, I have two functions, first function is to display total items in to cart and second function list all products in cart.

How can I return this two function's html output back from AJAX?

Here is the php server side:

<?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);
?>

And this is the AJAX call method:

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(){

                        }
                    });
                }
            }
        });
    }
 });
});

My question is how to return this two html contents function from AJAX?

I used json_encode() to return but I get no luck

Please help...!

  • 写回答

1条回答 默认 最新

  • dqyq88053 2015-03-28 12:29
    关注

    You are echoing the html out instead of storing it in a string. To fix this, the fastest way is to redirect the echo outputs to a php variable:

    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);
    

    With ob_start and ob_get_clean you redirect the echo from the standard outputbuffer to a variable. And by that you can put the variable content into your json data.

    Further, with json-data as response, you need to use dataType: 'json' in your ajax call:

     $.ajax({
       /* ... */
       dataType: "json",
       /* ... */
     });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao