使用JSON API获取数据时遇到的问题:
我使用的请求方法是:“http://www.example.org/?json=get_post&post_id=47。”
但是,返回的JSON文件附带了<script>
块,这导致了一个问题:
<script>
document.cookie="kentopvc_22238=yes";
</script>
<script>
document.cookie="kentopvc_22238=yes";
</script>
{"status":"ok","post":{"id":22238,"type": ........... }
答案 0 :(得分:1)
如果您无法访问返回格式错误数据的API,则需要使用Regex捕获该字符串,然后对其进行解析。
var jsonString = response.match(/^{.*$/m)[0]
var parsedJson = JSON.parse(jsonString)
正则表达式解释
/ // beginning of pattern
^ // starts at the beginning of a new line
{ // looks for a bracket immediately following a new line
.* // any subsequent characters
$ // until we reach the end of the line
/ // end of pattern
m // the 'multiline' flag, necessary for the use of ^
[0] // match() returns matches in an array. we want the first (and in this case only) match