I need to be able to retrieve and display JSON data from a website for the application I am making. Before implementing it into my application, I thought I should make sure I understand how it works by testing it elsewhere. I made the following HTML and JSON code to test it, but if I run the application I get Uncaught TypeError: Cannot read property '0' of undefined at file:///android_asset/www/projectName.html:11 What am I doing wrong?
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.get('testData.json', function(data) {
alert('get performed');
var obj = eval ("(" + data + ")");
$("p").html(obj.data_set[0].data1);
});
});
});
</script>
</head>
<body>
<h2>Heading</h2>
<p>Display</p>
<button>Click me</button>
</body>
</html>
JSON file:
[{"data_set":{"data1":"string","data2":null,"data3":22.0}}]
Change the $.get
to $.getJSON
or set the datatype in your $.get called like this
UPDATE
I also realized that you're not parsing the json correctly tried like this
$.get('testData.json', function(data) {
alert('get performed');
$("p").html(obj[0].data_set.data1);
},'json');
You're using eval
which is unnecessary. I suggest you read about what JSON is and how to use it .
You don't need to use eval
on data
because it is already a JSON object. The problem with your code is that you're trying to access data_set
as a property of data
. However, data
is really an array, with one unnamed object. That object has the member data_set
. In turn, data_set
is an object, not an array, so you cannot use data_set[0]
. You want to have something like:
$(document).ready(function(){
$("button").click(function(){
$.getJSON('testData.json', function(data) {
alert('get performed');
$("p").html(data[0].data_set.data1);
});
});
});
Check out this jsfiddle
See this jsFidle: http://jsfiddle.net/7Uxtg/
I included some code to traverse the whole data-structure (not just one possible path). Take the part you need ;-)
$(document).ready(function () {
$("button").click(function () {
$.ajax({
url: '/gh/gist/response.json/37ab4c69a04628428ce2',
dataType: 'json',
success: function (json) {
// to display everything
/*$.each(json, function (k, v) {
$.each(v.data_set, function (key, value) {
$('p').append(value);
});
});*/
// to display just the string
$('p').html(json[0].data_set.data1);
}
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.