【问题标题】:remove quotation mark in ajax response删除ajax响应中的引号
【发布时间】:2020-03-19 02:02:34
【问题描述】:

响应返回为"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);
                            }
                    }
            }

【问题讨论】:

  • 你从服务器发送什么?听起来像是某处额外的 stringify() 。
  • @zipzit 更新了问题,请看一下
  • 我在考虑服务器端 php。您在哪里将 $cart_ 数量作为响应发送回客户? json_encode ??
  • @zipzit 是的,json_encode
  • 这是answer 我的问题。

标签: javascript ajax


【解决方案1】:

数据不是真正的 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>

【讨论】:

  • 它现在什么都不显示。控制台看不到错误
  • 它说“8”字符串
  • 它说“8”和引号
  • 现在用引号表示“数字”
  • 但它仍然显示在我的元素上的引号
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 2018-08-23
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2019-11-01
相关资源
最近更新 更多