JSON.parse获取值

时间:2015-09-14 13:31:46

标签: jquery json ajax response

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

let parseAudio: PFFile = objects.valueForKey("Songs") as? PFFile
parseAudio?.getDataInBackgroundWithBlock({ (data, error) -> Void in

      if error == nil {
             // do what you need to with the music file which is contained in `data`
              let fullParseAudioFile = data

      } else if error != nil {

      println(error!.localizedDescription)

      }

  })

我正在接受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");
    }
});

提前致谢。

2 个答案:

答案 0 :(得分:0)

我看到了什么错误:

  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);
        }
    },
    

答案 1 :(得分:0)

@jai是正确的,因为您的响应类型是json所以您的“响应”变量已经包含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");
    }
});