jQuery AJAX GET 不适用于本地 JSON 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9066335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AJAX GET not working with local JSON file?
提问by Xtian
I had a JSONP URL, that was pulling data and just switched to a local JSON file and now I am getting errors. I don't understand why it is not working with a local JSON file?
我有一个 JSONP URL,它正在提取数据并刚刚切换到本地 JSON 文件,现在出现错误。我不明白为什么它不能使用本地 JSON 文件?
<script type="text/javascript">
$.ajax({
type : 'GET',
dataType : 'json',
url: '/json/topics.json',
success : function(data) {
console.log(data);
var topics = [];
$.each(data.results, function(index, obj){
topics.push({
username: obj.TopicName,
mentions: obj.LastHourCount,
totalcount: obj.TotalCount,
daycount: obj.Last24HoursCount
});
});
$('#leader').tmpl(topics).appendTo('#top3');
}
});
</script>
In the console it is saying AJAX is a anonymous function for some reason? Any suggestions?
在控制台中它说 AJAX 出于某种原因是一个匿名函数?有什么建议?
采纳答案by jk.
$.ajax
is asynchronous and it looks like you are trying to change the DOM on page load, add
$.ajax
是异步的,看起来您正在尝试在页面加载时更改 DOM,添加
async: false,
to your $.ajax
parameters. Note that it may slow down page load.
到你的$.ajax
参数。请注意,它可能会减慢页面加载速度。
Example:
例子:
$.ajax({
type : 'GET',
dataType : 'json',
async: false,
// rest of your code
See this post if you are using local files, not through webserver, and getting a Origin null is not allowed by Access-Control-Allow-Origin
error:
如果您使用的是本地文件,而不是通过网络服务器,并且出现Origin null is not allowed by Access-Control-Allow-Origin
错误,请参阅此帖子:
错误:使用 JQuery 的 ajax 方法加载 XML 文件时,“Access-Control-Allow-Origin 不允许使用 Origin null”