JQuery get() or getJSON only work for local files

2019-09-20 05:28发布

I'm tring to load a test.json file from my server. The index.html which trys to load that file is on another server(infact its a local file).

$url = 'test.json';    
$.getJSON($url, function(data) {
    for (var i = 0, len = data.length; i < len; i++) {
             //some code
    }
});

works perfect. but when i set $url = 'http://simonappelt.de/test.json' it doesn't do anything. I also tried the get() function to get files from my server but they seam to load nothing.

Thanks Simon

3条回答
Viruses.
2楼-- · 2019-09-20 05:31

Typically you can only make an AJAX request (which is what $.getJSON is) on the same domain and protocol as your script. If you wish to make a cross-domain request, you will must use the JSON-P support of $.getJSON, and wrap the data in a callback invocation server side, determined by the query string parameter, ?callback.

查看更多
祖国的老花朵
3楼-- · 2019-09-20 05:51

From the jQuery $.getJSON documentation....

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

查看更多
4楼-- · 2019-09-20 05:52

Ajax requests can only be made to the same domain as the current document. The ajax url should be a local one. Can read more about this at http://www.webreference.com/programming/javascript/understanding-ajax/index.html.

查看更多
登录 后发表回答