Accessing an External JSON File, Example 1 (p. 157)
This example uses JSON to represent a single playing card:
a) create a folder, ~/Documents/repos/281/examples/ch5/
b) create a folder, ~/Documents/repos/281/examples/ch5/javascripts
c) create a folder, ~/Documents/repos/281/examples/ch5/cards
d) Open our textbook’s ch5 Example 1 repo in Chrome
Download index.html to ~/Documents/repos/281/examples/ch5/
Download aceOfSpades.json to ~/Documents/repos/281/examples/ch5/cards/
e) Download this version of app.js from p. 157 to ~/Documents/repos/281/examples/ch5/javascripts/
f) In Atom, open ~/Documents/repos/281/examples/ch5/
Testing the Web App
Use Atom’s Open in Browser command to open index.html, and then view the cross-origin error message in the DevTools console.
- The file:// protocol violates the web’s same-origin policy:
For the security reasons described on p. 156, requests will only succeed if they are made to the same server that served the original web page. The XHR error reported is, “XMLHttpRequest cannot load file aceOfSpades.json. Cross-origin requests are only supported for protocol schemes: http, https, ….“
- AJAX web apps must be served using the HTTP protocol.Ch. 5 describes how you can preview an AJAX app by turning off your browswer’s security restrictions. This is not generally a good idea, so we will avoid it.
- Option 1: upload the app to uoregon.edu, and test it.
- Option 2: use Node.js and Express to serve the app from your computer.
Accessing an External JSON File, Example 2 (p. 158)
This example uses JSON to represent an array of five playing cards:
Chapter5/Example1, p. 158. Download app.js to ~/Documents/repos/281/examples/ch5/javascripts.