Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^276) CHAPTER 18 ■ AJAX AND JSON


JSON and JavaScript


To work with Ajax, JSON, and PHP, you need to know a little about JavaScript. For a moment,
let’s focus on some useful and required JavaScript libraries and functions.
If you haven’t done so already, download http://www.json.org/json.js now. You will
need this script to use the examples in this chapter. This script provides the client-side encoding
functions and an alternative parser to eval() that will throw exceptions, rather than client
JavaScript errors, if it gets bad data. This script provides two key methods that enhance the
JavaScript language itself:

string type.toJSONString(): This method applies to most of the built-in JavaScript types.
It will return a JSON-encoded string representing the data in the type. Listing 18-2 demon-
strates its use.

mixed string.parseJSON(filter): This method restores a JSON-encoded string to a
JavaScript structure and will throw an exception if there is a problem decoding the data.
Building on Listing 18-2, Listing 18-3 demonstrates how to decode a JSON-encoded value.

Listing 18-2. JavaScript JSON Encoding

<html>
<head>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
function showJsonData() {
original = new Array(0, 1, 2, 3);

//Encode original in JSON returning a string.
json = original.toJSONString();

div = document.getElementById("jsonData");
div.innerHTML = json;
}
</script>
</head>
<body>
<a href="#" onclick="showJsonData()">Show JSON Data</a>
<div id="jsonData"></div>
</body>
</html>

[0,1,2,3]

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

Free download pdf