跨域 JSONP 请求返回 Uncaught SyntaxError: Unexpected token :
您好,我正在尝试从 API 获取数据。
我使用 ajax 调用,但总是收到错误消息 未捕获的语法错误:意外的标记:
任何人都可以给我一个如何进行正确的 jsonp 调用的示例。
下面是我的代码片段。我正在使用 CoffeeScript,
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"
)
如有任何帮助,我们将不胜感激。谢谢
Hi I am trying to get a data from an API.
I use an ajax call but then I always get an error message
Uncaught SyntaxError: Unexpected token :
can anyone give me an example of how to do a correct jsonp call.
below is my code snippet. I am using coffeescript
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"
)
any help is appreciated. Thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的 JSON 是什么样的?听起来好像是畸形的。 此处进行验证。
另外,使用 jQuery 的 $.getJSON ,您不需要指定回调函数,它会为您生成一个随机名称,您可以像平常一样使用
success()
回调。What does your JSON look like? Sounds like it's malformed. Validate it here.
Also with jQuery's
$.getJSON
you don't need to specify a callback function, it will generate a random name for you and you can use thesuccess()
callback like normal.对于 $.getJSON URL 字符串,附加 '?callback=dummyDummy',其中 dummyDummy 是将用作回调函数名称的任何字符串值;您不需要在其他地方定义 dummyDummy。我测试成功的 jQuery 版本是 1.5.1。
With the $.getJSON URL string, append '?callback=dummyDummy' where dummyDummy is any string value that will be used as callback function name; you do not need to define dummyDummy anywhere else. Version of jQuery I had tested successfully with is 1.5.1.