【问题标题】:Error: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data错误:JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束
【发布时间】:2017-11-22 03:06:52
【问题描述】:

我有以下代码,用于将产品添加到购物车,但每次我将产品添加到购物车时,产品都会添加到购物车,但我收到错误:意外结束JSON数据的第1行第1列的数据显示在Firefox中。 现在在 chrome 中,我收到错误:Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at Object.success

我已经尝试使用 console.log 但 php 没有返回给我任何错误。试了好几个办法都解决不了,所以来这里求助。

jQuery:

$(document).ready(function () {

//add a product in the cart
$('#add-to-cart').click(function () {

    $("#addtocartform").submit(function(e) {
    var prod_id = $("#add-to-cart").data("id");
    var prod_mode = $("input[name=course_mode]:checked").val();


    $.ajax
        ({
            url: '/cart/add',
            type: 'POST',
            data: jQuery.param({ prod_id: prod_id, prod_mode: prod_mode}),
            dataType: 'text',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            success: function (data) {
                //console.log(data);
                var frontend_cart_result = JSON.parse(data);
                $('#dropdowncart').html( frontend_cart_result['cart_li'] );
                $('.badge').text( frontend_cart_result['cart_item_quantity'] );
                $(location).attr('href', '/checkout');

            },
            error: function () {
                alert("error");
            }

        });
         e.preventDefault(); // avoid to execute the actual submit of the form.
        });
});

})

PHP:路径 /cart/add

public function add() {

    //session_destroy();
    //$_SESSION['cart'][0]['id'] = 'teste'; 

    $cart_go = true;
    if (!empty($_SESSION['cart'])) {

        foreach ($_SESSION['cart'] as $valor) {
            if ($valor['id'] == $_POST['prod_id']) {
                $cart_go = false;
            }
        }
    }

    if ($cart_go) {

        $db = new productModel();

        //check if product has already been added
        if (!empty($_SESSION['cart'])) {
            $next_key = max(array_keys($_SESSION['cart']));
            $next_key++;
        } else {
            $next_key = 0;
        }

        $_SESSION['cart'][$next_key] = $db->selecionaproduto(array("prod_id" => $_POST['prod_id']));
        //add all the products filds in session
       //bought the online course
        if ($_POST['prod_mode'] == 1) {

            $_SESSION['cart'][$next_key]['classroom_price'] = '';
        }
        //bought the classroom course
        if ($_POST['prod_mode'] == 2) {

            $_SESSION['cart'][$next_key]['online_price'] = '';
        }


        $frontend_cart = '';


        foreach ($_SESSION['cart'] as $valor2) {

            $frontend_cart = $frontend_cart . '<li>
                  <span class="item">
                      <span class="item-left">
                          <img src="/web-files/img/course/' . $valor2['id'] . '/' . $valor2['top_nav_cart_thumbnail'] . '" alt="">
                          <img src="/web-files/img/course/' . $valor2['id'] . '/' . $valor2['top_nav_cart_thumbnail'] . '" alt="">
                          <span class="item-info">
                              <span>' . $valor2['name'] . '</span>
                              <span><strong>R$ ' . number_format($valor2['online_price'] . $valor2['classroom_price'], 2, ',', '.') . '</strong></span>
                          </span>
                      </span>
                      <span class="item-right">
                          <button data-id="' . $valor2['id'] . '" class="btn btn-xs btn-danger pull-right delete-cart-item">x</button>
                      </span>
                  </span>
              </li>';
        }

        $frontend_cart = $frontend_cart . '<li class="divider"></li>
                                  <li><a class="text-center" href="/checkout">Cart</a></li>
                                  <li class="divider"></li>
                                  <li><a class="text-center" href="/checkout">Checkout</a></li>';


        $frontend_cart_result = array(
            "cart_li" => $frontend_cart,
            "cart_item_quantity" => count($_SESSION['cart'])
        );

        echo json_encode($frontend_cart_result);
    }
}

这是控制台日志

{"cart_li":"<li>\r\n                      <span class=\"item\">\r\n                          <span class=\"item-left\">\r\n                              <img src=\"\/web-files\/img\/curso\/1\/psicofarmacologia-na-infancia-e-adolescencia-top-nav-cart.jpg\" alt=\"\">\r\n                              <span class=\"item-info\">\r\n                                  <span>Curso de atualiza&ccedil;&atilde;o em psicofarmacologia na inf&acirc;ncia e adolesc&ecirc;ncia<\/span>\r\n                                  <span><strong>R$ 999,00<\/strong><\/span>\r\n                              <\/span>\r\n                          <\/span>\r\n                          <span class=\"item-right\">\r\n                              <button data-id=\"1\" class=\"btn btn-xs btn-danger pull-right delete-cart-item\">x<\/button>\r\n                          <\/span>\r\n                      <\/span>\r\n                  <\/li><li class=\"divider\"><\/li>\r\n                                      <li><a class=\"text-center\" href=\"\/checkout\">Cart<\/a><\/li>\r\n                                      <li class=\"divider\"><\/li>\r\n                                      <li><a class=\"text-center\" href=\"\/checkout\">Checkout<\/a><\/li>","cart_item_quantity":1}

谢谢你!

【问题讨论】:

  • 你注释掉了//console.log(data); 什么是数据的价值?其他代码无关紧要......我们需要查看价值,很可能是格式错误
  • 不要猜测,validate your JSON 并解决您的具体问题。
  • 我在问题中包含了console.log(日期)
  • 我将 dataType 更改为 html,现在我没有收到更多错误
  • 数据类型应该是json

标签: php jquery json


【解决方案1】:

您告诉您的 ajax 调用期望 text 作为响应的数据类型。然后,您将在 PHP 脚本中创建 HTML 并对其进行 json 编码,然后再将其输出为对 ajax 请求的响应。

可能会出什么问题?

【讨论】:

  • 完美,我将 dataType 更改为 html,现在我没有收到更多错误,请给你这么多 miknik!
【解决方案2】:

我建议不要将 HTML 作为值存储在您的 json 响应中。

在您的 AJAX 请求中尝试:

dataType: 'json', 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-15
    • 2021-03-22
    • 2016-01-30
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多