Angularjs JSONP 不起作用 [英] Angularjs JSONP not working

查看:18
本文介绍了Angularjs JSONP 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能在这里遗漏了一些东西,但我无法使这个 JSONP 请求工作,这是代码:

I might be missing something here but I can't make this JSONP request work, here is the code:

var url =  'http://' + server + '?callback=JSON_CALLBACK';
$http.jsonp(url)
    .success(function(data){
       console.log('success');
    })
    .error(function () {
      console.log('error')
    });

请求触发正常,我收到以下格式的响应(带有标题 Content-Type:application/json):

The request fires ok and I am getting the response (with header Content-Type:application/json) in this format:

    [{"id": "1", "name": "John Doe"},
     {"id": "2", "name": "Lorem ipsum"},
     {"id": "3", "name": "Lorem ipsum"}]

你能看出什么问题吗?也许我应该从服务器返回的格式不对?Angular 会触发错误回调,除了我设置的错误消息('error')之外没有任何错误消息.

Can you see anything wrong? Maybe the format I should return from the server is not right? Angular fires the error callback without any error message besides the one I set ('error').

推荐答案

JSONP requires you将您的数据包装到 JavaScript 函数调用中.因此,从技术上讲,您返回的是 JavaScript 文件,而不是 Json 文件.

JSONP requires you do wrap your data into a JavaScript function call. So technically you return a JavaScript file and not a Json file.

服务器返回的数据应该是这样的:

The data returned from server should similar to this:

// the name should match the one you add to the url
JSON_CALLBACK([
    {"id": "1", "name": "John Doe"},
    {"id": "2", "name": "Lorem ipsum"},
    {"id": "3", "name": "Lorem ipsum"}
]);

编辑:如果其他人在 Angular 的 JSONP 中遇到问题,请同时阅读 此问题的答案,它包含有关 angular 如何处理实际回调函数的有用信息.

Edit: If some one else stumbles across problems with angular's JSONP please also read this answer to this question, it contains usefull informations about how angular handles the actual callback function.

这篇关于Angularjs JSONP 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆