【问题标题】:Reading JSON data with jquery. Uncaught SyntaxError: Unexpected token :使用 jquery 读取 JSON 数据。 Uncaught SyntaxError: Unexpected token :
【发布时间】:2016-05-28 14:34:57
【问题描述】:

我正在尝试使用 jquery 读取 JSON 数据。具体来说,我正在尝试从此网址读取 JSON:http://mkweb.bcgsc.ca/color-summarizer/?url=http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10643840_701797013239098_657737630_a.jpg&precision=low&num_clusters=3&json=1&callback=?
但是我不断收到此错误: Uncaught SyntaxError: Unexpected token :
这是我的jQuery:

$(document).ready(function () {

        var one = "1"

        $.getJSON('http://mkweb.bcgsc.ca/color-summarizer/?url=http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10643840_701797013239098_657737630_a.jpg&precision=low&num_clusters=3&json=1&callback=?', function(result) {

            document.write(result.clusters.one.rgb[0]);

        });
    });

我在 JSON 代码的第一个冒号处收到错误消息。
据我了解,JSON 数据实际上是作为 Javascript 读取的。我该如何解决这个问题。

【问题讨论】:

  • 该url不支持JSONP或者至少不支持提供callback=xyz参数。
  • 不相关,但您的var one 技巧不起作用。您需要使用result.clusters[one].rgb[0]result.clusters['1'].rgb[0]
  • 我添加了回调=?参数,因为我之前收到此错误No 'Access-Control-Allow-Origin' header is present on the requested resource.

标签: javascript jquery json


【解决方案1】:

阅读API Docs发现需要指定jsnop=1参数才能通过JSONP检索数据。

正确的代码应该是这样的:

    $(document).ready(function () {         
        $.ajax({
            url: 'http://mkweb.bcgsc.ca/color-summarizer/',
            type: 'GET',
            dataType: 'jsonp',
            jsonpCallback: 'colorsummary',
            data:{
                url: 'http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10643840_701797013239098_657737630_a.jpg',
                precision: 'low',
                num_clusters: '3',
                jsonp: '1'
            },
            success: function(result){
                document.write(result.clusters['1'].rgb[0]);
            }
        });
    }); 

我还对请求进行了结构化,以便您可以轻松更改参数。

PS:注意那个 JSON 符号(集群中的 ['1'] 等等)

【讨论】:

  • 没有。参考 API 文档,$.getJSON() 是 ajax 调用的简短句柄。见api.jquery.com/jquery.getjson
  • 我说的是颜色汇总 API。我使用 $.ajax() 只是为了更轻松地管理请求。
猜你喜欢
  • 2011-12-17
  • 1970-01-01
  • 2011-04-02
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多