Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 18 ■ AJAX AND JSON^277

■Caution If in the development of your site you have used JavaScript for..in loops to analyze the properties
of objects, be sure that you’ve also checked for the proper ownership. All for..in loops should contain an
object.hasOwnProperty() check so that inherited properties are not unexpectedly encountered.

Listing 18-3. Parsing JSON in JavaScript

<html>
<head>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
function showJsonData() {
original = new Array('first', 'second', 'third');
json = original.toJSONString();
div = document.getElementById("jsonData");

//Decode JSON, and set div.innerHTML
//to the first element in the array
div.innerHTML = json.parseJSON()[0];
}
</script>
</head>
<body>
<a href="#" onclick="showJsonData()">Show JSON Data</a>
<div id="jsonData"></div>
</body>
</html>

first

The optional filter parameter of parseJSON() allows you to create a function that will
filter the resulting key/value pairs and apply some sort of translation to the value. Listing 18-4
shows an example of using the optional filter parameter to convert the value to a JavaScript
date object, where the key is equal to 'date'.

Listing 18-4. Using the parseJSON filter Parameter

<html>
<head>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
function convertDates(key, value) {

McArthur_819-9.book Page 277 Friday, February 29, 2008 8:03 AM

Free download pdf