AJAX GET not working with local JSON file?

别说谁变了你拦得住时间么 提交于 2020-01-13 06:02:07

问题


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>

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


回答1:


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

async: false,

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

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:

Error: "Origin null is not allowed by Access-Control-Allow-Origin" when loading an XML file with JQuery's ajax method



来源:https://stackoverflow.com/questions/9066335/ajax-get-not-working-with-local-json-file

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