0

I want to display data from an external JSON file on a webpage.

data.json:

{"users":[
    {
        "firstName":"S",
        "lastName":"S",
        "joined": {
            "month":"January",
            "day":12,
            "year":2012
        }
    },
    {
        "firstName":"S",
        "lastName":"P",
        "joined": {
            "month":"April",
            "day":28,
            "year":2010
        }
    }
 ]}

html code is as follows:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Sample</title>
</head>
<body>
    <div id="placeholder"></div>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
  $.getJSON('data.json', function(data) {
        var output="<ul>";
        for (var i in data.users) {
            output+="<li>" + data.users[i].firstName + " " + data.users[i].lastName + "--" + data.users[i].joined.month+"</li>";
        }

        output+="</ul>";
        document.getElementById("placeholder").innerHTML=output;
  });
    </script>
</body>hello world
</html>

When i run this code as it is on chrome I get the following error:

XMLHttpRequest cannot load file:///C:/Users/.../jsonJquery/data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

However, the same code runs on Firefox. I am not able to figure out what exactly is going wrong with the same code on two different browsers.

On changing the html code to access the file from the web, I get the Cross-Origin error(this happens on both firefox and chrome)

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Sample</title>
</head>
<body>
    <div id="placeholder"></div>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
  $.getJSON('www.someDomain.com/data.json', function(data) {
        var output="<ul>";
        for (var i in data.users) {
            output+="<li>" + data.users[i].firstName + " " + data.users[i].lastName + "--" + data.users[i].joined.month+"</li>";
        }

        output+="</ul>";
        document.getElementById("placeholder").innerHTML=output;
  });
    </script>
</body>hello world
</html>

My question is what is the reason of these errors? Is there some other way to access data that is placed remotely?

UPDATE: The JSONP implementation works fine! Thanks!

What I am trying to implement is to add accordion groups dynamically(by reading from a JSON file). But I keep getting the error:

'Uncaught TypeError: $(...).accordion is not a function'

Below is my code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="external/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="external/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="external/jquery.ui.widget.min.js"></script>
<script>

(function($) {
var url = 'http://www.someDomain.com/data.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
       var $bar = $( "#accordion" ).accordion();
       $bar.accordion('clearGroups');
       $.each(data, function(id, group){
        $bar.accordion('addGroup', group);
        });
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

</script>
<style type="text/css">
.widget
{
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<div id="accordion" class="widget"></div>
</body>
</html>

Can someone help me out with it?

I am sure that this must be some syntactical error, but I am not able to figure it out! :(

ss7389
  • 85
  • 2
  • 12

2 Answers2

1

Use $.each() for manipulating json data :

$.getJSON('data.json', function(data) {
    var output = "<ul>";
    $.each(data.users, function(i, item) {
        output += '<li>' +
            item.firstName + ' ' +
            item.lastName + ' ' +
            item.joined.month +
            '</li>'
    });
    output += "</ul>";
    document.getElementById("placeholder").innerHTML = output;
});

Also for cross origin error, add callback=? GET parameter to your url in $.getJSON.

but in general you have to implement JSONP to get it done right.

Refrences :

http://www.w3schools.com/jquery/ajax_getjson.asp

jquery loop on Json data using $.each

jQuery AJAX cross domain

Community
  • 1
  • 1
0

Use withCredentials option for cross-domain request, this will help avoid a cross-origin error:

$.ajax({
    url: "http://www.someDomain.com/data.json",
    type: "GET",
    dataType: 'json',
    xhrFields: {
         withCredentials: true
    }
}.done(function() {
   // your code here
});
marsh
  • 1,431
  • 1
  • 13
  • 19