you’re on your way �
399
parting gifts
#5: Using eval() with JSON
In Chapter 7, you saw how you can use the eval() function to evaluate
JSON returned from a server-side script:
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var jsonData = eval(‘(‘ + request.responseText + ‘)’);
// Get the updated totals from the XML response
var totalBoards = jsonData.totals[0].boardsSold +
jsonData.totals[1].boardsSold +
jsonData.totals[2].boardsSold +
jsonData.totals[3].boardsSold;
The eval() function
takes a JSON response,
and converts it into a
JavaScript object.
The problem with eval() is that it runs the JSON response from the
server without any security checks... if some malicious organization was
able to tamper with your server’s response, you could end up running some
harmful code in your JavaScript.
Use a JSON parser
If you’re concerned about security with JSON, you may want to use a
JSON parser, and avoid using eval() in your JavaScript functions.
Where to get it: http://www.json.org/js.html
How to use it:
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var jsonData = JSON.parse(request.responseText);
// Get the updated totals from the XML response
var totalBoards = jsonData.totals[0].boardsSold +
You’ll have to reference the JSON.js le
you download from the json.org web site.
using <script> ...