I am getting the error " Uncaught SyntaxError: Unexpected token ':' " on line 2 in my JSON file.
Here is the HTML I am using. I acquired both the HTML and JSON from "https://css-tricks.com/dynamic-dropdowns/". Their demo works great so I wanted to try it for myself but I am having issues getting it to work on my desktop.
<!DOCTYPE html>
<head>
<meta charset='UTF-8'>
<title>Dynamic Dropdown</title>
<link rel='stylesheet' href='css/style.css'>
<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> -->
</head>
<body>
<div id="page-wrap">
<h1>Pulls from text files</h1>
<select id="text-one">
<option selected value="base">Please Select</option>
<option value="beverages">Beverages</option>
<option value="snacks">Snacks</option>
</select>
<br />
<select id="text-two">
<option>Please choose from above</option>
</select>
<h1>Pulls from JSON</h1>
<select id="json-one">
<option selected value="base">Please Select</option>
<option value="beverages">Beverages</option>
<option value="snacks">Snacks</option>
</select>
<br />
<select id="json-two">
<option>Please choose from above</option>
</select>
</div>
<script src="?\jsondata\data.json">
$(function() {
$("#text-one").change(function() {
$("#text-two").load("textdata/" + $(this).val() + ".txt");
});
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("jsondata/data.json", function(data) {
var key = $dropdown.val();
var vals = [];
switch(key) {
case 'beverages':
vals = data.beverages.split(",");
break;
case 'snacks':
vals = data.snacks.split(",");
break;
case 'base':
vals = ['Please choose from above'];
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});
});
});
});
</script>
</body>
</html>
Here is the JSON I am using that is getting the error.
{
"beverages": "Coffee,Coke",
"snacks": "Chips,Cookies"
}
Please help.
<script>
elements are for loading JavaScript , not JSON.
You are getting an error because the browser is trying to execute it as JS which it isn't.
Remove the src
attribute from the <script>
element.
Use Ajax to fetch the JSON. Then parse it into a JS object. The body of the <script>
element (currently ignored because you gave it a src
) is trying to do that.
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.