HTML and CSS Reference
In-Depth Information
Suppose that the web server somehow sends the following JSON string:
{
"name" : "Vangos Pterneas",
"message" : "Hello world!"
}
Obviously, the preceding notation contains two key-value pairs. Guess what? In your
chat demo, it represents the chat data received from another user. You are going to
use this information in a few minutes.
Following code shows how you can handle a JSON object and extract its properties:
socket.onmessage = function(event) {
if (typeof event.data === "string") {
// Create a JSON object.
var jsonObject = JSON.parse(event.data);
// Extract the values for each key.
var userName = jsonObject.name;
var userMessage = jsonObject.message;
}
}
The preceding code is straightforward. Using the eval function, you create a JSON
object from the input string. What eval really does is invoke the JavaScript compiler
and execute the enclosed string arguments. The properties of the generated object
are the names of the JSON keys and each property holds its corresponding value.
XML
Similar to JSON, you can parse XML-encoded strings using JavaScript. We won't go
deeper into XML parsing, as this would be out of this topic's scope. Parsing XML is
not difficult, though it requires different techniques for different browsers ( DOMPars-
er versus ActiveXObject ). The best method is using a third-party library such as
jQuery .
Search WWH ::




Custom Search