简体   繁体   English

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

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

I'm doing an e-commerce and I implemented an AJAX request to add and remove items from the cart dinamically. 我正在做一个电子商务,我实现了一个AJAX请求,以动态方式添加和删除购物车中的商品。 Everytime the jQuery is executed everything works fine , It always returns 200 OK but the error event is fired instead of success. 每次执行jQuery时, 一切工作正常 ,它始终返回200 OK,但会触发错误事件,而不是成功。

That's how it works: 这就是它的工作方式:

Everytime the user click the "Add to Cart" button, the Jquery will check if this item is available, then will INSERT, ADD or Return Error: 每次用户单击“添加到购物车”按钮时,Jquery都会检查此项目是否可用,然后将执行INSERT,ADD或Return Error:

  • Status 1 = Product Inserted into Cart (Empty Cart, First time this product is added) 状态1 =产品已插入购物车(空购物车,首次添加此产品)
  • Status 2 = Product added to Cart (This product is already on Cart, add +1) 状态2 =产品已添加到购物车(此产品已在购物车中,添加+1)
  • Status 3 = Not Enough Stock (All the products already on Cart) 状态3 =库存不足(所有产品已在购物车中)

jQUERY CODE 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 CODE (addCart.php) 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));

Every time the code is executed everything works as it should, the items are added to the cart, all the INSERTS and UPDATES are done, it always returns 200 OK BUT the error event is fired instead of success. 每次执行代码时,一切都会正常进行,将项目添加到购物车,完成所有的INSERTS和UPDATES操作,它始终返回200 OK, 会触发错误事件,而不是成功。

IMPORTANT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 重要/////////////////////////////////////////////////// ///////////////////////////////////////////////////// /////////////////////////////////////////

The strings $status and $status_txt (addCart.php) never return empty values, they always return an integer and a text message. 字符串$ status$ status_txt (addCart.php)从不返回空值,它们始终返回整数和文本消息。 To avoid empty values ( "" ) parse error. 为了避免空值( “” )解析错误。

THINGS I ALREADY TRIED BUT DID NOT WORK: ////////////////////////////////////////////////////////////////////////// 我已经尝试过但无法使用的东西://///////////////////////////////////////// /////////////////////////////////

  • Remove (dataType: "json") 删除(数据类型:“ json”)
  • Change the dataType: "json" to "text" 将dataType:“ json”更改为“ text”
  • Force a Header ('Content-Type: application / json'); 强制标题(“ Content-Type:应用程序/ json”);
  • Use exit (); 使用exit(); after json_encode 在json_encode之后
  • Check if my JSON is valid or not on external sites, ie: jsonlint.com 检查我的JSON在外部站点上是否有效,即: jsonlint.com

I've managed an workaround that temporarily fix my problem. 我已经设法解决了暂时解决我的问题的方法。 I used Javascript substr() , to get the Status number on error responseText and then made all the validations on the Ajax Error Event: 我使用Javascript substr()获取错误responseText上的状态编号,然后对Ajax错误事件进行了所有验证:

JAVASCRIPT WORKAROUND 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"); }

    }

Where responseText return the Json result: 其中responseText返回Json结果:

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

And using substr() will return the status number (1, 2 or 3): 并且使用substr()将返回状态号(1、2或3):

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

I know it's not the right way to handle this, that's why I want to fix this error that's driving me nuts... 我知道这不是处理此问题的正确方法,这就是为什么我要修复导致我发疯的错误...

What I'm doing wrong? 我做错了什么? I've used this code several times and I've never had this problem before, I've read tons of similar questions here on StackOverflow but none of them worked for me... 我已经使用过几次该代码,而且之前从未遇到过这个问题,我在StackOverflow上阅读过很多类似的问题,但是它们对我来说都不起作用...

Any help is appreciated! 任何帮助表示赞赏!

Your JSON response body is invalid. 您的JSON响应正文无效。 This can be seen in your comment ... 这可以在您的评论中看到...

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

That "Array" prefix is not valid and is typically an indicator of accidental array-to-string conversion in PHP, prior to where you echo JSON. 该“数组”前缀无效,通常表示在echo JSON之前在PHP中意外的数组到字符串转换。 For example 例如

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

When developing, you should always run PHP with error-reporting set to the highest level. 开发时,应始终在将错误报告设置为最高级别的情况下运行PHP。 Displaying errors in your output is also the quickest way to be alerted. 在输出中显示错误也是最快的警报方式。

You have two options... 您有两个选择...

  1. In your development environment's php.ini file, set 在开发环境的php.ini文件中,设置

     error_reporting = E_ALL 

    and

     display_errors = On 
  2. In your code 在你的代码中

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

This should help you track down any accidental output (which it did). 这应该可以帮助您跟踪任何意外输出(确实如此)。


Also, you were missing out on vital information in your client-side error handler. 此外,您还错过了客户端错误处理程序中的重要信息。 The signature for the callback is 回调的签名是

Function( jqXHR jqXHR, String textStatus, String errorThrown )

You can gain some valuable insight with something as simple as 您可以通过以下简单的方法获得一些有价值的见解:

console.error(textStatus, errorThrown)

worked for me 为我工作

addCart.php addCart.php

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

and in the AJAX request 并在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