AJAX GET not working with local JSON file?

36.8k views Asked by At

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

There are 1 answers

6
jk. On BEST ANSWER

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