即使json_encode正确并且一切正常,Ajax请求总是会触发错误 [英] Ajax Request always fire error even when json_encode is right and everything work as it should

查看:96
本文介绍了即使json_encode正确并且一切正常,Ajax请求总是会触发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行电子商务,我实施了一个AJAX请求,以便在购物车中添加和删除商品。每次jQuery执行一切正常,它总是返回 200 OK 但错误事件被触发而不是成功。

I'm doing an e-commerce and I implemented an AJAX request to add and remove items from the cart dinamically. Everytime the jQuery is executed everything works fine, It always returns 200 OK but the error event is fired instead of success.

这就是它的工作原理:

每当用户点击添加到购物车按钮时, Jquery将检查此项是否可用,然后将INSERT,ADD或Return Error:

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:


  • 状态1 =产品已插入购物车(空购物车,第一次添加此产品)

  • 状态2 =产品已添加到购物车(此产品已在购物车上,加入+ 1)

  • 状态3 =库存不足(所有产品已在购物车上)

  • Status 1 = Product Inserted into Cart (Empty Cart, First time this product is added)
  • Status 2 = Product added to Cart (This product is already on Cart, add +1)
  • Status 3 = Not Enough Stock (All the products already on Cart)

jQUERY CODE

$.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 BUT 错误事件被触发而不是成功。

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.

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

字符串 $ status $ status_txt (addCart.php)永远不会返回空值,它们总是返回一个整数和一条短信。为了避免空值()解析错误。

The strings $status and $status_txt (addCart.php) never return empty values, they always return an integer and a text message. To avoid empty values ("") parse error.

我已经尝试过的但是没有工作:///// ////////////////////////////////////////////////// ///////////////////


  • 删除(dataType: json)

  • 将dataType:json更改为text

  • 强制标题('Content-Type:application / json') ;

  • 使用exit();在json_encode之后

  • 检查我的JSON在外部网站上是否有效,即: jsonlint.com

  • Remove (dataType: "json")
  • Change the dataType: "json" to "text"
  • Force a Header ('Content-Type: application / json');
  • Use exit (); after json_encode
  • Check if my JSON is valid or not on external sites, ie: jsonlint.com

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

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 WORKAROUND

    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结果:

Where responseText return the Json result:

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

使用 substr()将返回状态编号(1,2或3):

And using substr() will return the status number (1, 2 or 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...

我做错了什么?我已经多次使用过这段代码了,之前我从来没有遇到过这个问题,我在StackOverflow上看过很多类似的问题但是没有一个能为我工作......

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...

感谢任何帮助!

推荐答案

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

Your JSON response body is invalid. This can be seen in your comment...


我得到数组{status: 1,警告:产品已插入}

数组前缀无效且通常是PHP中意外数组到字符串转换的指示器,在此之前 c JSON。例如

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. For example

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

开发时,你应该总是运行PHP,并将错误报告设置为最高级别。在输出中显示错误也是提醒的最快方式。

When developing, you should always run PHP with error-reporting set to the highest level. Displaying errors in your output is also the quickest way to be alerted.

您有两种选择...


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

error_reporting = E_ALL

display_errors = On


  • 在你的代码中

  • 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)
    

    这篇关于即使json_encode正确并且一切正常,Ajax请求总是会触发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆