AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 147


PART I


You can then take that value and directly load it into the page using innerHTML:

var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = xhr.responseText;

Given that you are setting the innerHTML property of your output target, you are not
limited to plain text responses. You can of course include (X)HTML markup, inline styles,
and id or class values bound to existing style sheets in your responses as well. On the
server side, simply output the packet as so and make sure to label it with the appropriate
MIME type.

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/html");
echo "Thank you for voting. You rated this a <strong>$rating</
strong>. There are <strong>$votes</strong> total votes. The average is
<strong>$average</strong>. You can see the ratings in the <a href='http://
ajaxref.com/ch4/ratings.txt' target='_blank'>ratings file</a>";

The network trace of the response is as you would expect:

You can see the example in action at http://ajaxref.com/ch4/htmlresponse.html.
Sending responses directly to the document will work only in some situations, but when
appropriate, it is quite useful. This isn’t the end of our standard XHTML markup discussion;
we’ll revisit it later when we discuss responseXML.
Free download pdf