开发者

Why does this .json file not get parsed by jquery?

开发者 https://www.devze.com 2023-02-15 08:49 出处:网络
I have uploaded this data to rackspace cloud files: {\"foo\": \"bar\"} It lives at this url: http://c192531.r31.cf1.rackcdn.com/test.json

I have uploaded this data to rackspace cloud files:

{"foo": "bar"}

It lives at this url: http://c192531.r31.cf1.rackcdn.com/test.json

It is served as Content-Type application/json, and when accessed with a browser you get a promt to download. The file has the expected content.

When I try to access it with jquery 1.4.2 with this snippet

<script>
$(document).ready(function($) {

    url = 'http://c192531.r31.cf1.rackcdn.c开发者_StackOverflow社区om/test.json';
    $.getJSON(url, function (data) {
        alert( data );
    });

});
</script>

it alerts null.

What did I do wrong?


Is the page containing this script hosted on the same domain (http://c192531.r31.cf1.rackcdn.com)? If not you are probably hitting the same origin policy restriction which prevents you from sending cross domain AJAX requests.

A possible workaround would be to use JSONP but you will need to make the remote URL return a JSONP string or if you cannot modify it setup a server side script which would act as a bridge between your domain and the remote domain and then send the AJAX request to this bridge script.


You're running into the Same Origin Policy. You can download the JSON directly because you're not attempting to do so from within another site's context (i.e., you're simply accessing the URL directly). But from within the ajax request, you have http://site.a attempting to load data from http://site.b.


This is due to the security restruction. A way around this is using jsonp instead of just json.

In jquery, you can leverage jsonp by setting the content type to jsonp. But you do need to change your json file.


You cannot request a JSON file that is not on the same domain as the page. This is called the same origin policy. You can use JSONP though.

0

精彩评论

暂无评论...
验证码 换一张
取 消