Java Reference
In-Depth Information
15.2
Working with Ajax Requests and Responses
Using JavaScriptResolution is convenient for using JavaScript on the
client side to do something with the response to an Ajax request. You
can also transfer data in other formats, such as JSON or XML. 1
However, if all you're doing in response to an Ajax request is updating
a portion of the page, it can become cumbersome to construct HTML
in JavaScript code using the values obtained in the response. I'll go
even further and say that doing this makes me feel like I'm back in
1998, with only servlets at my disposal and having to construct HTML
in Java code!
Fortunately, there's a much easier way. You can send HTML fragments
in response to Ajax requests and use them directly to update a portion
of the page. What makes this very convenient is that you can construct
the HTML in a regular JSP, using all the goodness of Stripes, action
beans, and everything else you've learned. The only difference is that
the JSP renders a fragment instead of a complete page.
Automatic Page Portion Update
The idea of updating a page portion with the HTML fragment returned
by the server is illustrated in Figure 15.2 , on page 343 . Prototype's
Ajax.Updater sends an Ajax request and automatically updates the iden-
tified element ( 'result' , in this example) with the response data.
Continuing the “double your money” example, say we just had an empty
element to contain the result:
Download ajax/web/WEB-INF/jsp/updater.jsp
<p> Let me double your money! </p>
<p>
<s:form beanclass="stripesbook.action.UpdaterActionBean">
You give me $
<s:text name="youGiveMe" onkeyup="sendMoney(this);"/>
<s:submit name="doubleMoney"/>
</s:form>
</p>
<p id="result"></p>
</s:layout-component>
</s:layout-render>
1. In fact, that's why it's “Asynchronous JavaScript and XML”; initially XML was the
main format used when transferring data in Ajax responses. Other formats have emerged
since then; besides JavaScript code such as returned by JavaScriptResolution , JavaScript
Object Notation (JSON, http://www.json.org ) is also popular.
 
 
 
Search WWH ::




Custom Search