【问题标题】:Can't access data in JSON format after REST callREST 调用后无法访问 JSON 格式的数据
【发布时间】:2017-05-17 20:39:31
【问题描述】:

我访问了一个将数据作为 JSON 对象返回的 Web 服务。据我了解,JSON 已经被解析,所以我应该能够简单地访问数据。但每次我尝试时,我都会返回 undefined。

这是代码:

xhr.open("GET", requestString, true);
xhr.send();

myThing = xhr.response.cod;
console.log(myThing)

这是请求:

任何我认为真实的东西似乎都返回“未定义”。搜索后,我发现结果应该已经解析为 JSON 并且我应该能够访问它。我做错了什么?

【问题讨论】:

标签: javascript json rest


【解决方案1】:

由于异步,您的代码需要如此结构化,read more:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.onload = function () {
  // Request finished. Do processing here.
  var data = JSON.parse(xhr.response);
  console.log(data.cod);
};

xhr.send(null);
// any kind of "return" or operation down here that expects xhr.response to exist will *FAIL*

【讨论】:

  • 感谢您的回复,我能够通过记录xhr.responseText 将结果打印到控制台,但是当我尝试将其保存到变量中,然后在结果之后打印该变量打开并发送xhr.send(null),我仍然不确定。 responseText 不能单独保存到变量中吗?
  • 当然,只要确保您在 onload 函数中执行此操作即可。但是您将无法退回它,您的其他代码也不知道它何时可用。通常最好在回调中对 ajax 响应执行所有操作。
  • 那么,如何从 onload 函数中返回的 JSON 中提取数据呢?我正在尝试重试简单的元素,例如 xhr.response.cod,但它仍然返回 undefined...
  • 我已经有一段时间没有使用“裸”xhr 对象(通常是 jQuery)了,所以我希望我的编辑是有效的,请试一试。
  • 哦,快。我现在明白了。我必须在xhr.responseText 上使用JSON.parse,在onload 函数内,然后我可以像JSON 对象一样访问它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
相关资源
最近更新 更多