【问题标题】:JSON Array and Objects length handled differently in Chrome and Internet ExplorerJSON 数组和对象长度在 Chrome 和 Internet Explorer 中的处理方式不同
【发布时间】:2018-10-17 17:01:25
【问题描述】:

在 XMLHttpRequest 之后,一个函数会遍历 .records JSON,但是它只能在 chrome 或 Internet Explorer 中工作,不能同时在两者中工作。 问题在于.length 属性。

在 chrome 中,当我这样做时它可以工作:

 request1.response.records.length
 1438

在 Internet Explorer 中,我只能访问整个 JSON 正文,而不是 .records 的值,这在 chrome 中不起作用。

request1.response.length 
30158

问题中的 JSON 开头为:

"{
  "total":null,
   "records":[{
  "id":"5465464865",
  "parentId": "545465",...

【问题讨论】:

  • 在响应中发布调用JSON.parse() 的代码。

标签: javascript json xmlhttprequest iteration


【解决方案1】:

似乎 Internet Explorer 没有将您的响应解释为 Javascript 对象,而 Chrome 可以推断它并将响应视为 JS。我不确定这是否是您的问题,但请尝试指定您希望收到的 response type,如下所示:

var xhr = new XMLHttpRequest();
xhr.responseType = 'json'; //check if you have this line, add it if you don't

【讨论】:

  • 好像确实是这样,但是responsetype已经设置好了。
  • 好的!我刚刚做了一些搜索,似乎这是 IE11 中的一个错误(这是您使用的版本吗?):github.com/naugtur/xhr/issues/123。我不确定如何避免该错误,也许您可​​以使用eval('var res = '+request1.response+';') 并使用已评估的res 变量而不是request1.response,但我知道这看起来很hacky,并且eval 可能是邪恶的。不管怎样,试一试吧,也许它会在短期内解决你的问题。
  • 您的回答帮助我找到了这个解决方法:if (typeof answer === 'string') { answer = JSON.parse(answer); }
  • 太好了,这比eval 方法好得多,谢谢分享!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 2011-10-28
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多