duancai7568 2017-11-21 10:36
浏览 223
已采纳

错误:JSON.parse:JSON数据的第1行第1列的意外数据结束

I have the following code below, that I use to add products to the cart, but every time I add a product to the cart, the product is added to the cart, but i'm getting the error: unexpected end of data at line 1 column 1 of the JSON data is shown in firefox. Now in chrome, i'm getting the error: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at Object.success

I already tried to use console.log but php is not returning to me any errors. I tried several solutions but I could not solve them, so I came to ask for help here.

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: Path /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);
    }
}

here is the console.log

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

Tank you!

展开全部

  • 写回答

2条回答 默认 最新

  • dongtazu3080 2017-11-21 10:54
    关注

    You are telling your ajax call to expect text as the data type of the response. You are then creating HTML in your PHP script and json encoding it before you output it as a response to the ajax request.

    What could possibly go wrong?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 IBMP550小型机使用串口登录操作系统
  • ¥15 关于#python#的问题:现已知七自由度机器人的DH参数,利用DH参数求解机器人的逆运动学解目前使用的PSO算法
  • ¥15 发那科机器人与设备通讯配置
  • ¥15 Linux环境下openssl报错
  • ¥15 我在使用VS编译并执行之后,但是exe程序会报“无法定位程序输入点_kmpc_end_masked于动态链接库exe上“,请问这个问题有什么解决办法吗
  • ¥15 el-select光标位置问题
  • ¥15 单片机 TC277 PWM
  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部