jquery post check json response


jquery post check json response

有一个脚本,它将产品添加到cart会话中,php将响应返回到jquery post函数。问题是我无法检查返回的响应来运行一些动画。

我的jquery代码是:

var product = {
            action: 'shs_add_to_cart',
            'nonce': wp_nonce_value,
            'product': product_id,
            'title': product_title,
            'qty': quantity.val()
        };
        $.post(
          shsAjaxURL.ajaxurl, product,
          function(status) {
            var response = $.parseJSON(status);
            console.log('response');
            if(response == 'success') {
              message.find('p').text('Item added to cart');
              message.fadeIn(300);
              message.delay(2500).fadeOut(300);
            }
            else {
              message.find('p').text('Could not add to cart');
              message.fadeIn(300);
              message.delay(2500).fadeOut(300);
            }
        });

PHP代码在为会话车添加值时运行良好

 $_SESSION['cart_items'] = array(
                array(
                    'item_id'   => $product,
                    'item_name' => $title,
                    'item_qty'  => $qty
                )
        );
        header('Content-Type: application/json');
        echo json_encode('success');
        wp_die();

我得到以下响应

"success"

有人能帮忙吗?

使用dataTypejson更改ajax,如下所示:

$.ajax({
      url:shsAjaxURL.ajaxurl,
      data: product,  
      dataType: 'json',
      type: 'post',
      success:function(data) {
         console.log(data.success);
      }
   });

然后在您的php代码中:

$_SESSION['cart_items'] = array(
                array(
                    'item_id'   => $product,
                    'item_name' => $title,
                    'item_qty'  => $qty
                )
        );
        $data['success'] = "success";
        echo json_encode($data);