Angular simple JSON request

this will probably make me look like a total beginner and I am when it comes to angular, but here's my question:

I'm trying to make a simple request to a .JSON api but I just keep getting the error status code 0.

var dataUrl = 'http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2';

$http({method: 'GET', url: dataUrl}).
    success(function(data, status, headers, config)
    {
        window.alert('success:' + status);
    }).
    error(function(data, status, headers, config) {
        window.alert('error:' + status);
    });

Update:

I checked the javascript console via the browser and got these error messages:

event.returnValue is deprecated. Please use the standard event.preventDefault() instead. Failed to load resource: the server responded with a status of 501 (Not Implemented) http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2 Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access. http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2 XMLHttpRequest cannot load http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access.


You are trying to do a cross-domain request. This is forbidden by browser (it will only let you make requests to the same domain as your page was initially loaded from). This is not specific to angular, but just ajax requests in general.

You can read about it here:

http://en.wikipedia.org/wiki/Same-origin_policy

There are several ways around it, such as JSONP and CORS. Both require server-side support. You would have to look at the service you are calling to see which it might support.

You can read about how to do a JSONP request here:

http://docs.angularjs.org/api/ng.$http


You are not allowed to access resource on another website.

You need to use jsonp.

This is an un-tested modified code of yours, please try it to see whether it's working or not:

var dataUrl = 'http://www.reddit.com/r/pics/comments/1ua1nb/.json?jsonp=JSON_CALLBACK&limit=2';

$http.jsonp(dataUrl).
    success(function(data, status, headers, config)
    {
        window.alert('success:' + status);
    }).
    error(function(data, status, headers, config) {
        window.alert('error:' + status);
    });

more to read: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

链接地址: http://www.djcxy.com/p/20130.html

上一篇: Eclipse Neon Json编辑器

下一篇: 角度简单的JSON请求