繁体   English   中英

即使json_encode是正确的并且一切正常,Ajax Request总是会引发错误

[英]Ajax Request always fire error even when json_encode is right and everything work as it should

我正在做一个电子商务,我实现了一个AJAX请求,以动态方式添加和删除购物车中的商品。 每次执行jQuery时, 一切工作正常 ,它始终返回200 OK,但会触发错误事件,而不是成功。

这就是它的工作方式:

每次用户单击“添加到购物车”按钮时,Jquery都会检查此项目是否可用,然后将执行INSERT,ADD或Return Error:

  • 状态1 =产品已插入购物车(空购物车,首次添加此产品)
  • 状态2 =产品已添加到购物车(此产品已在购物车中,添加+1)
  • 状态3 =库存不足(所有产品已在购物车中)

j查询代码

$.ajax({

    type: "GET",
    url: "addCart.php",
    data: { id: id, color: color },
    dataType: "json",

    success: function(result){ 
        if (result.status == 1){ alert("Product Inserted into Cart"); }
        if (result.status == 2){ alert("Product Added to Cart"); }
        if (result.status == 3){ alert("Not enough Stock"); }
    },

    error: function (result) {
        alert(result.responseText)
    }   

});

PHP代码(addCart.php)

## I REMOVED NON-RELEVANT CODES TO SIMPLIFY THIS QUESTION BUT ALL VALIDATIONS
## HAVE ALREADY BEEN DONE, THEN RETURN THE JSON RESPONSE...

if ($status == 1){
    $status_txt = "Product Inserted into Cart";

}elseif ($status == 2){
    $status_txt = "Product Added to Cart";

}elseif ($status == 3){
    $status_txt = "Not enough stock";

}

echo json_encode(array("status" => $status, "alert" => $status_txt));

每次执行代码时,一切都会正常进行,将项目添加到购物车,完成所有的INSERTS和UPDATES操作,它始终返回200 OK, 会触发错误事件,而不是成功。

重要/////////////////////////////////////////////////// ///////////////////////////////////////////////////// /////////////////////////////////////////

字符串$ status$ status_txt (addCart.php)从不返回空值,它们始终返回整数和文本消息。 为了避免空值( “” )解析错误。

我已经尝试过但无法使用的东西://///////////////////////////////////////// /////////////////////////////////

  • 删除(数据类型:“ json”)
  • 将dataType:“ json”更改为“ text”
  • 强制标题(“ Content-Type:应用程序/ json”);
  • 使用exit(); 在json_encode之后
  • 检查我的JSON在外部站点上是否有效,即: jsonlint.com

我已经设法解决了暂时解决我的问题的方法。 我使用Javascript substr()获取错误responseText上的状态编号,然后对Ajax错误事件进行了所有验证:

JAVASCRIPT解决方案

    error: function (result) {

        status = result.responseText.substr(10, 1); 
        if (status == 1){ alert("Product Inserted into Cart"); }
        if (status == 2){ alert("Product Added to Cart"); }
        if (status == 3){ alert("Not enough Stock"); }

    }

其中responseText返回Json结果:

{"status":1,"alert":"Product inserted to Cart"}

并且使用substr()将返回状态号(1、2或3):

status = result.responseText.substr(10, 1); 

我知道这不是处理此问题的正确方法,这就是为什么我要修复导致我发疯的错误...

我做错了什么? 我已经使用过几次该代码,而且之前从未遇到过这个问题,我在StackOverflow上阅读过很多类似的问题,但是它们对我来说都不起作用...

任何帮助表示赞赏!

您的JSON响应正文无效。 这可以在您的评论中看到...

我得到Array{"status":1,"alert":"Product Inserted"}

该“数组”前缀无效,通常表示在echo JSON之前在PHP中意外的数组到字符串转换。 例如

echo [1,2,3]; // Notice: Array to string conversion in ...

开发时,应始终在将错误报告设置为最高级别的情况下运行PHP。 在输出中显示错误也是最快的警报方式。

您有两个选择...

  1. 在开发环境的php.ini文件中,设置

     error_reporting = E_ALL 

     display_errors = On 
  2. 在你的代码中

     ini_set('display_errors', 'On'); error_reporting(E_ALL); 

这应该可以帮助您跟踪任何意外输出(确实如此)。


此外,您还错过了客户端错误处理程序中的重要信息。 回调的签名是

Function( jqXHR jqXHR, String textStatus, String errorThrown )

您可以通过以下简单的方法获得一些有价值的见解:

console.error(textStatus, errorThrown)

为我工作

addCart.php

<?php
// your inserts and checking here.    
$str = json_encode(array("status" => $status, "alert" => $status_txt));
echo $str;

并在AJAX请求中

$.ajax({
  url: 'ajax/addCart.php',
  type: 'POST',
  data: { id: id, color: color },
  dataType: 'json',
  success: function(res){
     console.log(res['status']);
     if (res['status'] == 1) {
       console.log('nice');
     }
  },
  error: function(s) {
     console.log(s.responseText);
  }
});

暂无
暂无

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

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