If I have a JSON
file named names.json with:
{\"employees\":[
{\"firstName\":\"Anna\",\"lastName\":\"Meyers\"},
{\"firstNam
In the jQuery code, you should have the employees
property.
data.employees[0].firstName
So it would be like this.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.getJSON("names.json", function(data) {
console.log(data);
$('body').append(data.employees[0].firstName);
});
</script>
</body>
</html>
Of course you'll need that property for the non jQuery version too, but you'd need to parse the JSON response first.
Also keep in mind that document.write
is destroying your entire page.
If you're still having trouble, try the full $.ajax
request instead of the $.getJSON
wrapper.
$.ajax({
url: "names.json",
dataType: "json",
success: function(data) {
console.log(data);
$('body').append(data.employees[0].firstName);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}
});
http://api.jquery.com/jquery.ajax/