JSON.parse 获取值

JSON.parse get values

在继续执行脚本之前,我需要检查 JSON 响应中的一个值,但它不起作用。

$.ajax({
    type: "POST",
    url: "addproduct.php",
    data: {productId : selectedValue, customerId : customerId},
    datatype: "json",
    success: function (response) {
        response = JSON.parse(response);
        if(response === undefined) {
            alert("undefined");
        } else if (response.pricelistupdate = 1) { //this doesn't work
            alert("ERROR! Adding a product is denied");
        } else {
            orderAddRow(response);
        }
    },
    error: function () {
        alert("ERROR");
    }
});

我正在关注 JSON 回复:

{"row":{"pricelistupdate":0,"ID":"000017","name":"Chair","discount":"0.00","price":"0.00"}}

提前致谢。

我看到了什么错误:

  1. 您不需要 JSON.parse(),因为 datatype:"json" 就在那里。
  2. pricelistupdate的引用应该是response.row.pricelistupdate
  3. 不是将 === 与一个值进行比较,而是在 elseif.
  4. 中将其分配给 =

因为你有 dataType:

datatype: "json",

所以你不需要解析 json。你可以删除它 response = JSON.parse(response);

JSON.parse() 方法只能用于 json 字符串,但在您的情况下,响应是有效的 json,因此您不需要它。

然后得到它:

您需要引用您的对象键并且您缺少键 row 并且您还缺少 =elseif 中的等号:

else if (response.row.pricelistupdate === 1) 

所以在你的成功回调中必须是这样的:

success: function (response) {
    if(response === undefined) {
        alert("undefined");
    } else if (response.row.pricelistupdate === 1) { // check "===" equals
        alert("ERROR! Adding a product is denied");
    } else {
        orderAddRow(response);
    }
},

@jai 是正确的,因为你的响应类型是 json 所以你的 "response" 变量已经包含 json 所以首先删除

 response = JSON.parse(response);

看到你的回复,你的回复存储在行对象中所以你访问 "pricelistupdate" 不正确你应该用 response.row.pricelistupdate 替换它所以你的最终代码看起来像

$.ajax({
    type: "POST",
    url: "addproduct.php",
    data: {productId : selectedValue, customerId : customerId},
    datatype: "json",
    success: function (response) {
        if(response === undefined) {
            alert("undefined");
        } else if (response.row.pricelistupdate = 1) { 
            alert("ERROR! Adding a product is denied");
        } else {
            orderAddRow(response.row);
        }
    },
    error: function () {
        alert("ERROR");
    }
});