Hi,
I'm wondering if someone can clue me in on why I cannot access json data by using a variable as a node name.
I'm trying to grab a random quote from a .json file and display it in a div. When I access a node in the object by node name I can access the node data. However, when I try to use a variable in place of the node name (because I want to grab a random node) I get an object undefined error.
Any help is appreciated
Thanks!
JSON object:
- {
"quote1" : {"quote" : "hello, world."},
"quote2" : {"quote" : "goodbye, world."},
"quote3" : {"quote" : "out of this world."}
}
HTML:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Title</title>
<script src="js/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
var randNo = Math.floor((3-0)*Math.random()) + 1;
var randQuote = "quote" + randNo;
var indexQuotes = "json/quotes.json";
$(document).ready(function()
{
$.ajax(
{
async: false,
url: indexQuotes,
dataType: "json",
success: function(data)
{
// alert(randQuote);
// $(".results").html(data.quote1.quote)
$(".results").html(data.randQuote.quote)
}
});
});
</script>
</head>
<body>
<div class="results"></div>
</body>
</html>