【问题标题】:Can't parse Json result from jQuery Ajax POST无法解析来自 jQuery Ajax POST 的 Json 结果
【发布时间】:2019-05-28 02:02:10
【问题描述】:

如果我将结果写入控制台并将其复制到字符串变量(jsonInput)中,我会通过 Ajax 从 REST API 获取 JSON。JSON.parse 工作正常,但如果我直接使用数据(ajax 结果)它是未定义的。我检查了两个变量并且相等?

let jsonInput = 
  '{"pollId":49,
    "question":"sdf",
    "multipleAnswer":0,"answers":
     [{"pollAnswerId":69,"answer":"sdf"},
      {"pollAnswerId":70,"answer":"fsdf"}]}'

console.log(data === jsonInput); //TRUE

json = JSON.parse(data); //undefined

json = JSON.parse(jsonInput); //succesfull parsed

【问题讨论】:

标签: jquery json ajax post


【解决方案1】:

不要将它作为字符串引用。这是一个对象。

let jsonInput = {...}

【讨论】:

    【解决方案2】:

    虽然您还没有用完整的代码定义您的问题。 但这可能是 data 是字符串而不是 JSON 对象的原因之一。

    【讨论】:

      【解决方案3】:

      我想我找到了主要问题,json 是用数据初始化的,但是外部的 .ajax json 是未定义的

             let json;
             $.ajax({
              url : "http://localhost:4040/api/"+id,
              type: "POST",
              success: function(data){
                 console.log(data); //works fine
                 json = data;
                 console.log(json); //works fine
              }
          });
          console.log(json); //undefined
      

      【讨论】:

      • Ajax 是异步的。这是预期的行为。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2014-07-01
      相关资源
      最近更新 更多