Jquery getJSON Not Working Cross Site

亡梦爱人 提交于 2019-12-02 11:45:24

问题


I have a piece of javascript that grabs JSON data. When executed locally everything seems to work fine. However, when I try accessing it from a different site, it doesn't work.

Here's the script.

$(function(){
    var aT = new AjaxTest();
    aT.getJson();
});

var AjaxTest = function()
{
    this.ajaxUrl = "http://mydeveloperpage.com/sandbox/ajax_json_test/client_reciever.php";

    this.getJson = function(){
        $.getJSON(this.ajaxUrl, function(data){
            $.each(data, function(i, piece){
                alert(piece);
            });
        });
    }
}

You can find a copy of the exact same file at "http://mydeveloperpage.com/sandbox/ajax_json_test/".

Any help would be greatly appreciated.

Thanks!


回答1:


From the 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.

  • Script and JSONP requests are not subject to the same origin policy restrictions.

You're going to need to use JSONP to get past the same-origin policy. jQuery can make this seamless (see the rest of the aforementioned documentation page).



来源:https://stackoverflow.com/questions/3038862/jquery-getjson-not-working-cross-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!