• Aucun résultat trouvé

Example Using JSON

Dans le document Foundations of Ajax (Page 92-98)

The following example is a simple demonstration of how to use JSON to translate JavaScript objects to a string format and send the string to the server using Ajax techniques; the server will then create an object based on the string. The example has no business logic and little user interaction, as it focuses on the JSON techniques both on the client side and on the server side. Figure 3-7 shows a “stringified” Carobject.

Because this example is nearly identical to the previous POSTexamples, we’ll focus on the JSON-specific techniques. Clicking the form button invokes the doJSONfunction. This function first asks the getCarObjectfunction to return a new instance of a Carobject. You then use the JSON JavaScript library (freely available from www.json.org) to translate the Carobject into a JSON string that is then displayed in an alert box. The JSON-encoded Carobject is then sent to the server using the XMLHttpRequest object.

Thanks to the freely available JSON-to-Java library, coding the Java servlet that services the JSON request is simple. Better yet, since JSON bindings are available for every flavor of server technology, you can easily implement this example using any server-side technology.

The JSONExampleservlet’s doPostmethod services the JSON request. It first asks the readJSONStringFromRequestBodymethod to obtain the JSON string from the request body.

It then creates an instance of JSONObject, supplying the JSON string to the object constructor.

The JSONObjectautomatically parses the JSON string at object creation time. Once JSONObject is created, you can use the various getmethods to retrieve the object properties in which you’re interested.

You use the getStringand getIntmethods to retrieve the year, make, model, and color properties. These properties are concatenated to form the string that is returned to the browser and displayed on the page. Figure 3-8 shows the response from the server after read-ing the JSON object.

Listing 3-11 showsjsonExample.html, and Listing 3-12 shows JSONExample.java.

Figure 3-7.The “stringified”Carobject

Figure 3-8.The response from the server after reading the JSON string

Listing 3-11.jsonExample.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>JSON Example</title>

<script type="text/javascript" src="json.js"></script>

<script type="text/javascript">

var xmlHttp;

function createXMLHttpRequest() { if (window.ActiveXObject) {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

}

else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest();

} }

function doJSON() {

var car = getCarObject();

//Use the JSON JavaScript library to stringify the Car object var carAsJSON = JSON.stringify(car);

alert("Car object as JSON:\n " + carAsJSON);

var url = "JSONExample?timeStamp=" + new Date().getTime();

createXMLHttpRequest();

xmlHttp.open("POST", url, true);

xmlHttp.onreadystatechange = handleStateChange;

xmlHttp.setRequestHeader("Content-Type",

"application/x-www-form-urlencoded;");

xmlHttp.send(carAsJSON);

}

function handleStateChange() { if(xmlHttp.readyState == 4) {

if(xmlHttp.status == 200) { parseResults();

} } }

function parseResults() {

var responseDiv = document.getElementById("serverResponse");

if(responseDiv.hasChildNodes()) {

responseDiv.removeChild(responseDiv.childNodes[0]);

}

var responseText = document.createTextNode(xmlHttp.responseText);

responseDiv.appendChild(responseText);

}

function getCarObject() {

return new Car("Dodge", "Coronet R/T", 1968, "yellow");

}

function Car(make, model, year, color) { this.make = make;

this.model = model;

this.year = year;

this.color = color;

}

</script>

</head>

<body>

<br/><br/>

<form action="#">

<input type="button" value="Click here to send JSON data to the server"

onclick="doJSON();"/>

</form>

<h2>Server Response:</h2>

<div id="serverResponse"></div>

</body>

</html>

Listing 3-12.JSONExample.java package ajaxbook.chap3;

import java.io.*;

import java.net.*;

import java.text.ParseException;

import javax.servlet.*;

import javax.servlet.http.*;

import org.json.JSONObject;

public class JSONExample extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String json = readJSONStringFromRequestBody(request);

//Use the JSON-Java binding library to create a JSON object in Java JSONObject jsonObject = null;

String responseText = "You have a " + jsonObject.getInt("year") + " "

+ jsonObject.getString("make") + " " + jsonObject.getString("model") + " " + " that is " + jsonObject.getString("color") + " in color.";

response.setContentType("text/xml");

response.getWriter().print(responseText);

}

private String readJSONStringFromRequestBody(HttpServletRequest request){

StringBuffer json = new StringBuffer();

String line = null;

try {

BufferedReader reader = request.getReader();

while((line = reader.readLine()) != null) { json.append(line);

} }

catch(Exception e) {

System.out.println("Error reading JSON string: " + e.toString());

}

return json.toString();

} }

Summary

In this chapter, you explored the myriad methods by which the XMLHttpRequest object and server can communicate with each other. The XMLHttpRequest object can send requests using either the HTTP GETor POSTmethods, while the request data can be sent as a query string, XML, or JSON data. After handling the request, the server will typically respond by sending simple text, XML data, or even JSON data. Each format may be best suited for certain situations.

Ajax wouldn’t be particularly useful if you had no way to dynamically update the page’s contents based on the results of a request. Today’s modern browsers expose the contents of a Web page as an object model in accordance with the W3C DOM standards. This object model allows scripting languages such as JavaScript to add, update, and remove content on the page without the need for a round-trip to the server. While some quirks still exist, most Web pages written according to W3C standards and modified using standard JavaScript will behave iden-tically in any standards-compliant browser. Most of today’s modern browsers also support the nonstandard innerHTMLproperty, which can be used to update the elements on a Web page.

You are now familiar with the XMLHttpRequest object and how you can use it to seam-lessly communicate with the server. You also know how to update the Web page’s contents dynamically. What’s next?

Chapter 4 offers a glimpse into the endless possibilities now afforded by Ajax. It’s one thing to know how to use Ajax, but it’s a completely different thing to apply it in a useful set-ting. The next chapter introduces situations common to Web applications that are prime candidates for Ajax techniques.

Implementing

Dans le document Foundations of Ajax (Page 92-98)