【问题标题】:Cross Domain JSONP request returns Uncaught SyntaxError: Unexpected token :跨域 JSONP 请求返回 Uncaught SyntaxError: Unexpected token :
【发布时间】:2012-02-23 18:03:05
【问题描述】:

您好,我正在尝试从 API 获取数据。

我使用 ajax 调用,但总是收到错误消息 Uncaught SyntaxError: Unexpected token :

谁能给我一个如何正确调用 jsonp 的例子。

下面是我的代码 sn-p。我正在使用咖啡脚本

get_shipping:=>
    shipper_id = @datapayload['general'][0]['shipper']
    origin = @datapayload['general'][0]['origin']
    destination = @datapayload['general'][0]['destination']
    if shipper_id == '001'
      expedition = 2
    if shipper_id == '002'
      expedition = 1
    if shipper_id == '003'
      expedition = 5
    if shipper_id == '004'
      expedition = 6
    api_code = 'my_api_code'
    @url = 'http://www.ongkoskirim.com/api/0.2/?id=' + api_code + '&o=' + origin + '&d=' + destination + '&c=' + expedition + '&callback=jsonhandler'
    $.getJSON @url, (data)=>
      alert jsonhandler
    $.ajax(
      url:@url
      headers:{'Access-Control-Allow-Origin': '*'}
      crossDomain: 'true'
      type:'GET'
      dataType:'jsonp'
      jsonpCallback:'jsonhandler'
      success:(data)=>
        console.log data
      error:=>
        console.log "error"
    )

感谢任何帮助。谢谢

【问题讨论】:

  • 整个错误信息是什么?是$.getJSON$.ajax 惹麻烦了吗?
  • 两者都有问题
  • Uncaught SyntaxError: Unexpected token :
  • error 回调参数中是否有任何内容,或者在此之前发生过这种情况?
  • 它只是简单地向控制台返回“错误”

标签: jquery ajax coffeescript jsonp


【解决方案1】:

使用 $.getJSON URL 字符串,附加 '?callback=dummyDummy' 其中 dummyDummy 是任何将用作回调函数名称的字符串值;您不需要在其他任何地方定义 dummyDummy 。我成功测试的 jQuery 版本是 1.5.1。

【讨论】:

    【解决方案2】:

    您的 JSON 是什么样的?听起来它格式不正确。验证它here

    同样使用jQuery的$.getJSON你不需要指定回调函数,它会为你生成一个随机名称,你可以像平常一样使用success()回调。

    【讨论】:

    • 我已经尝试使用 $.getJSON 但它仍然返回错误消息。 json 来自第三方网站的 API,我已经对其进行了验证
    猜你喜欢
    • 2013-12-29
    • 1970-01-01
    • 2014-03-09
    • 2013-08-24
    • 1970-01-01
    • 2018-06-18
    • 2013-06-28
    • 1970-01-01
    • 2015-07-04
    相关资源
    最近更新 更多