删除 AJAX 响应中的引号



响应返回为"4",而不仅仅是4

我尝试将其更改为 .done(函数(数据((,但仍然有相同的结果

                        $.ajax({
                                url: "../api/ajax/addToCart.php",
                                type: "post",
                                data: data
                            })
                            .done(function(response) {
                                 // alert(response);
                                 $('#cart_counter').html(response);
                                // console.log(JSON.parse(response));
                                getCart();
                                // console.log(response);
                            });

AJAX 正在从此页面获取响应 添加到购物车.php

$sql1 = 'DELETE FROM temp_cart WHERE item_id = "'  . $item_id . '" AND temp_id = "' . $temp_id . '"';
            $result = $conn->query($sql1);
            {
                $sql2 = 'INSERT INTO temp_cart(temp_id, temp_name, temp_number, item_name, item_price, item_quantity, item_total, item_pic, item_id, date_expiry) VALUES ("' . $temp_id . '", "' . $temp_name . '", "' . $temp_number . '", "' . $item_name . '", "' . $item_price . '", "' . $item_quantity . '", "' . $total_row . '", "' . $item_pic . '", "' . $item_id . '", "' . $date_expiry . '" )';
                $result = $conn->query($sql2);
                    {
                        $sql = "SELECT count(item_quantity) as count_quantity FROM temp_cart WHERE temp_id='$temp_id'";
                        $resultb = $conn->query($sql);
                        while($rowb = $resultb->fetch_assoc())
                            {
                               $cart_counter=$rowb['count_quantity'];
                               echo json_encode($cart_counter);
                            }
                    }
            }

数据不是真正的 JSON 格式,而是当您将其作为 JSON 传回时被字符串化的数字,因此它最终成为字符串。只需根据需要将字符串解析为数字:

 $('#cart_counter').html(parseInt(response));

let counter = 4;
let json = JSON.stringify(counter);
console.log(json, `is a ${typeof json}`);
console.log(`...now a ${typeof parseInt(json)}`);
document.querySelector('#target').innerHTML = parseInt(json);
<div id="target"></div>

最新更新