duanrong6802 2013-09-02 22:50
浏览 67
已采纳

单击div A时异步更新div B.

I'm working on small ecommerce and I'm trying to update the item count in the cart as soon as an item is added to it.

I'm sure I'm missing one step because unless the page gets refreshed, the cart doesn't get updated.

Div to add item:

<div class="buy_button">
  <h2><a href="#" class="addtocart" id="<?php echo $item_id ?>">Add item</a></h2>
</div>

Div that needs to be updated asynchronously:

<div id="cart">

//SQL query to get count of items in table

<h2><?php echo $item_count ?></h2>
</div>

.

$(function() {
$(".addtocart").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
});

return false;
});
});

Here is ajax_add.php:

if($_POST['id']) {

//SQL query to save item in table 
//SQL query to count items in table

<div id="cart">
//SQL query to get count of items in table
    <h2><?php echo $item_count ?></h2>
</div>
}
  • 写回答

2条回答 默认 最新

  • dongque8332 2013-09-02 23:00
    关注

    First, your syntax is wrong and should be throwing an error in console.

    data: info,

    you have a trailing comma on the object you are passing to the ajax method.

    also, you have no callback function to handle the data. Considering the code you presented, you would update the count as such:

    $.ajax({
        type: "POST",
        url: "ajax_add.php",
        data: info,
        success: function (data) {
            $('#cart h2').text($(data).find('#cart h2').text());
        }
    });
    

    It would certainly be better to have ajax_add.php return a json object or just the updated count value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?