JQuery get() or getJSON only work for local files

2019-09-20 05:14发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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.