繁体   English   中英

如何获取JSON以成功解析XMLHttpRequest字符串?

[英]How to get JSON to successfully parse a XMLHttpRequest string?

我正在使用Goo.gl URL缩短器来缩短链接。 我用一个Json字符串sed,它返回这样的结果,该结果存储在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

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

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

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

请参阅JSON:为什么要转义正斜杠?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM