文章内容

2017/12/20 14:19:36,作 者: 黄兵

处理 JSON 出现错误Uncaught SyntaxError: Unexpected token :

$.ajax({
         url: "http://api.duoshuo.com/threads/counts.json?short_name=official&threads=4ff1cbc43ae636b72a00001d",
         dataType: "jsonp"
     }).done(function(data) {
         console.log('done');
     });

如果把 dataType 改成 JSON ,则会出现错误
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.
应该是无法跨域。
按理来说处理成功会在 console 显示'done',但是返回错误'Uncaught SyntaxError: Unexpected token :'
这是多说的 api ,地址显示如下:
{"response":{"4ff1cbc43ae636b72a00001d":{"thread_id":"1152923703633758877","channel_key":null,"thread_key":"4ff1cbc43ae636b72a00001d","comments":145,"reposts":0,"likes":28,"weibo_reposts":13,"qqt_reposts":7}},"options":{"comments_zero":"暂无","comments_one":"1条评论","comments_multiple":"{num}条评论"},"code":0}

似乎应该是能通过 JSON 校验的。如果没有办法,如何获取这个JSON 当中'comments'的值呢?(在这个 api 里 comments = 145)

先说解决方法,把 url 中的 counts.json 改为 counts.jsonp 即可。

下面简单说下原因。

使用 Ajax 获取 json 时,存在跨域限制,不能这样调用;而 jsonp 实际是请求一个 script,然后允许里面的代码。

使用 jsonp 方式,但返回结果确实 json,自然出错,无法运行

根据多说文档 http://dev.duoshuo.com/docs/50615732a834c63c56004257,其支持 jsonp 格式,你修改 api 格式即可。

比如访问 http://api.duoshuo.com/threads/counts.jsonp?short_name=official&threads=4ff1cbc43ae636b72a00001d&callback=theFunctionName 得到的就是所需的格式了。

theFunctionName({"response":{"4ff1cbc43ae636b72a00001d":{"thread_id":"1152923703633758877","channel_key":null,"thread_key":"4ff1cbc43ae636b72a00001d","comments":145,"reposts":0,"likes":28,"weibo_reposts":13,"qqt_reposts":7}},"options":{"comments_zero":"暂无","comments_one":"1条评论","comments_multiple":"{num}条评论"},"code":0});

具体到 jQuery 的 ajax 方法中,不用手动在 url 中指定 callback 字段,库会自动添加。当然为了利用缓存,也可以通过参数来指定,具体参考 jQuery ajax 的文档。


分享到:

发表评论

评论列表