Get a JSON file from URL, XMLHttpRequest cannot load error

二次信任 提交于 2019-12-08 08:49:04

问题


I need to read a JSON file from URL and display. I have read a lot of posts but still couldn't fix the problem.

url : http://webapp.armadealo.com/home.json

I face this error : XMLHttpRequest cannot load

The code is below

$.getJSON("http://webapp.armadealo.com/home.json", function(data){
alert(data);
});

I have tried adding to the url

&callback=?

and making it a jsonp, still no luck. I have also used

<meta http-equiv="Access-Control-Allow-Origin" content="*" />

still no luck.

Is there anything that we need to do at the server side? People who have faced such an error and have found a solution, Help me out please! Thanks a lot!


回答1:


You cannot make cross-domain AJAX requests like that due to security reasons. So if you want to load content from another domain, you will have to use a workaround: JSONP (more info, example)

Use the following code for the AJAX request:

$.ajax({
    url: 'http://webapp.armadealo.com/home.json',
    type: 'GET',
    jsonpCallback: 'myCallback',
    dataType: "jsonp",
    success: function(data) {
        console.log(data);
    }
});

In order for this to work, you will have to wrap the JSON data in parentheses and add the callback name at the beginning:

myCallback({ ... JSON ... })


EDIT: Just noticed you already tried to use JSONP... Well, at least the above code works for me, perhaps you want to give it a try. ;)



来源:https://stackoverflow.com/questions/11512171/get-a-json-file-from-url-xmlhttprequest-cannot-load-error

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