I am testing out some code and I have created a json file with the data.
The problem is that I'm getting "[object Object],[object Object]" in the alert. No data.
What I'm I doing wrong?
Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON("appData.json",function(results){alert(results);});
});
</script>
</head>
<body>
</body>
</html>
and here is the content of appData.json
[{"foo":"bar"},{"foo2":"blablabla"}]
Also, The index.html file and the json file are both on my desktop and I am running it from there.
please try like this:
$.getJSON("appData.json", function(results) {
$.each(results, function(index) {
alert(results[index].foo);
});
});
Well, you're getting an array of objects, and arrays and objects are data.
// v----first Object in the outer Array
alert(results[0].foo);
// ^----foo property of the first Object
It's just that an alert shows the default toString() values of the objects.
When you use $.getJSON, jQuery parsed the JSON text into JavaScript objects automatically. If you wanted the raw JSON, then make a $.get request instead.
If you want to iterate the Array, use a for loop, or one of the iteration methods from jQuery or the native API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With