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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置