Newbie here. I'm working with a database of apartment complexes and apartment units for an intro CS class and trying to build a web app using flask.
In application.py, I've got something like this:
locationdict =
{
"Complex A": [1, 2, 3],
"Complex B": [4, 5, 6]
}
JSONlocationdict = json.dumps(locationdict, sort_keys=True)
return render_template("start.html", JSONlocationdict=JSONlocationdict)
But nothing seems to work when I'm trying to access that data from the dictionary in JavaScript. The HTML page looks roughly like this:
<button onclick = "getUnits(this)" id="Complex A"> Complex A </button>
<script>
function getUnits(arg) {
var locationName = arg.getAttribute("id");
var JSONlocationdict = "{{ JSONlocationdict }}";
console.log(JSONlocationdict)
// In the console, this is what you see:
// {"Complex A": [1,2,3], "Complex B", [4,5,6]}
var obj = JSON.parse(JSONlocationdict);
console.log(obj); // this returns the error
// Then you see this in the console:
// Uncaught SyntaxError: Unexpected token & in JSON at position 1
// at JSON.parse (<anonymous>)
// at getUnits (start:88)
// at HTMLButtonElement.onclick (start:119)
var units = obj["Complex A"];
console.log(units);
// That last request to log to the console does nothing so far.
}
</script>
I've tried using different ways to convert the original dictionary into JSON like jsonify and json.loads() instead of dumps(). I have gone through piles and piles of entries on stackoverflow about SyntaxError: Unexpected token, but I can't seem to get anything to work. Any ideas??
The only thing that seems to work reliably is having two separate pages -- the first page where the user can select from a list of apartment complexes and then sending them to a second page where they can then pick the unit.
It would be nice if they could click a button for the apartment complex, and then have the list of units available at that complex get dynamically generated on the same page, though.