AJAX - The Complete Reference

(avery) #1

146 Part I: Core Ideas


Response Formats


Our discussion of response formats begins with the same general point as the request format
discussion: it really is up to you what data format you pass back and forth. To prove that point,
we provide the simple voting example (http://ajaxref.com/ch4/responseexplorer.html),
extended with a possibility of choosing from ten different response formats to be returned.

You see four primary types of responses possible: plain text, script related, XML, and
encoded. Similar to the request formats, each will have some ease of use considerations.
You’ll start first with the familiar text responses found in the XHR’s responseText property.

Text Responses


The XHR object has two properties to read response data from: responseText and
responseXML. We start first with responseText, which is the more flexible of the two as it
allows any text format you like. To demonstrate this we show examples using the request
formats seen previously.

Text and Markup Fragments
If you just plan on displaying the returned data in a Web page, it might be easiest to prepare
it for display on the server and send down the text or markup fragment to be directly
injected into the page in an as-is format. This send-and-use approach is commonly used in
Ajax applications and typically relies on the nonstandard but commonly supported
innerHTML property. For example in most of the rating examples, you passed back a simple
text string (http://ajaxref.com/ch4/plaintextresponse.html) in response to the user’s vote,
as shown by this server-side PHP fragment:

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/plain");
echo "Thank you for voting. You rated this a $rating. There are $votes
total votes. The average is $average.";

and its data transmission trace:
Free download pdf