繁体   English   中英

删除ajax响应中的引号

[英]remove quotation mark in ajax response

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

我尝试将其更改为 .done(function(data)) 但仍然有相同的结果

                        $.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 正在从这个页面 addToCart.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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM