【问题标题】:Getting Uncaught Syntax Error: Unexpected Token ':'获取未捕获的语法错误:意外的令牌':'
【发布时间】:2017-06-28 19:57:59
【问题描述】:

我正在发出 API 请求,但我不知道为什么会一直发生这种情况。

当我检查网络选项卡时,我请求的数据是正确的,但它不会在控制台中打印出来。

我正在使用 Musixmatch API

有什么想法吗?

              $.ajax({
                type: "GET",
                data: {
                  "apikey": musixmatch,
                  "q_track": song,
                  "q_artist": artist,
                  "format":"json",
                },
                url: "https://api.musixmatch.com/ws/1.1/matcher.track.get",
                dataType: "jsonp",
                contentType: 'application/json',
                success: function(response)
                {
                  console.log(response);
                }
              });

【问题讨论】:

  • 在哪一行出错?
  • 错误源于API,根本不返回JSONP,因此无法解析

标签: jquery json ajax get syntax-error


【解决方案1】:

你做错了!

documentation for the API 明确指出格式有三种选择,JSON、JSONP 和 XML。

由于您使用的是客户端代码,因此您希望使用 JSONP,但您不能告诉 jQuery 期待 JSONP,然后要求 API 只返回 JSON,您还必须将格式选项更改为 JSONP,以便 API 返回

$.ajax({
  type: "GET",
  data: {
    "apikey": 'musixmatch',
    "q_track": 'song',
    "q_artist": 'artist',
    "format": "jsonp",
  },
  url: "https://api.musixmatch.com/ws/1.1/matcher.track.get",
  dataType: "jsonp",
  contentType: 'application/json',
  success: function(response) {
    console.log(response);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • 谢谢你们收拾这个烂摊子!!
【解决方案2】:

代码中的错误:

  1. "format":"json", 此处不应有尾随逗号。
  2. 其次,尝试删除以下两行,它应该可以工作:

    dataType: "jsonp",
    contentType: 'application/json',
    

最后,如果上面的方法不行,请尝试做:

$.getJSON("https://api.musixmatch.com/ws/1.1/matcher.track.get", {
  "apikey": musixmatch,
  "q_track": song,
  "q_artist": artist,
  "format": "json"
}, function(response) {
  console.log(response);
});

上述方法是最好的,因为它专门用于从 API 获取 JSON 输出。这应该是正确的做法。

$.getJSON("https://api.musixmatch.com/ws/1.1/matcher.track.get", {
  "apikey": "",
  "q_track": "Hello",
  "q_artist": "Hi",
  "format": "json"
}, function(response) {
  console.log(response);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2011-04-07
    • 2014-05-09
    • 2014-11-24
    • 2012-09-07
    • 2015-03-21
    • 1970-01-01
    相关资源
    最近更新 更多