【问题标题】:How to get JSON to successfully parse a XMLHttpRequest string?如何让 JSON 成功解析 XMLHttpRequest 字符串?
【发布时间】:2012-10-25 19:17:57
【问题描述】:

我正在使用 Goo.gl URL 缩短器来缩短链接。我给它发送了一个 Json 字符串,它返回这样的结果,这些结果存储在 xmlHttp.response 中:

"{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/mR2d",
 "longUrl": "http://google.com/"
}"

发送代码后,我尝试使用 JSON 解析它:

 xmlHttp.send(jsonStr);
 var short_url = JSON.parse(xmlHttp.response).id ; 

当此代码在函数中运行时,我收到以下“输入意外结束”错误:

getShortURL("http://google.com");
SyntaxError: Unexpected end of input
arguments: Array[0]
get message: function () { [native code] }
get stack: function () { [native code] }
set message: function () { [native code] }
set stack: function () { [native code] }
type: "unexpected_eos"
__proto__: Error

我原以为字符串中的引号可能有问题。什么是解决问题的好方法?

【问题讨论】:

  • 你的意思是 :var short_url = JSON.parse(xmlHttp.response.id) ; eval() 有效吗?
  • JSON 周围没有真正的引号,是吗?请发布实际响应,我不敢相信它是无效的 JSON
  • 你不能用纯 JavaScript 做到这一点,因为调用谷歌的服务需要一个帖子,而且他们不支持 JSONP。
  • 能否在解析 JSON 之前剪掉开头和结尾的引号?
  • 是的,console.log 在大多数浏览器中就是这样做的——它们显示引号以表明它是一个字符串,但不要转义内容——它们只是按原样打印,包括换行符等. 这意味着您的 JSON 实际上是有效的,您能否向我们展示整个错误消息?

标签: javascript json xml-parsing xmlhttprequest


【解决方案1】:

我想我意识到出了什么问题。该代码尝试在 XMLHttpRequest 实际有任何信息之前从它获取信息。需要等到 xmlHttp.onreadystatechange 和 xmlHttp.readyState == 4 再取出缩短的 URL。然后可以发送到需要的地方。

(不习惯这种异步问题...)

【讨论】:

    【解决方案2】:

    JSON: why are forward slashes escaped?

    我的猜测是,您使用的 JSON 解析器可能期望正斜杠被转义。看看这个输入是否被接受:

    {
        "kind": "urlshortener#url",
        "id": "http:\/\/goo.gl\/mR2d",
        "longUrl": "http:\/\/google.com\/"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多