AJAX GET无法与本地JSON文件一起使用? [英] AJAX GET not working with local JSON file?

查看:88
本文介绍了AJAX GET无法与本地JSON文件一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSONP URL,该URL提取数据并刚刚切换到本地JSON文件,现在出现错误.我不明白为什么它不能与本地JSON文件一起使用?

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?

<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>

在控制台中,由于某种原因,AJAX是一个匿名函数吗? 有什么建议吗?

In the console it is saying AJAX is a anonymous function for some reason? Any suggestions?

推荐答案

$.ajax是异步的,似乎您正在尝试在页面加载时更改DOM,添加

$.ajax is asynchronous and it looks like you are trying to change the DOM on page load, add

async: false,

您的$.ajax参数.请注意,这可能会减慢页面加载速度.

to your $.ajax parameters. Note that it may slow down page load.

示例:

 $.ajax({
    type : 'GET',
    dataType : 'json',
    async: false,
    // rest of your code

如果您使用本地文件(而不是通过Web服务器)并出现Origin null is not allowed by Access-Control-Allow-Origin错误,请参见此帖子:

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:

错误:"; Access-Control-Allow-Origin不允许原始null.使用JQuery的ajax方法加载XML文件时

这篇关于AJAX GET无法与本地JSON文件一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆