jQuery in Action
256
CHAPTER 8
Talk to the server with Ajax
<body>
<fieldset>
<legend>Initiate Ajax Requests</legend>
<div>
<button type="button" id="goodButton">
Initiate successful request
</button>
<button type="button" id="badButton">
Initiate failed request
</button>
</div>
</fieldset>
<fieldset>
<legend>Success display</legend>
<div id="successDisplay"></div>
</fieldset>
<fieldset>
<legend>Error display</legend>
<div id="errorDisplay"></div>
</fieldset>
</body>
The ready handler for the page has three tasks:
1
Set up the click handlers for the buttons
2
Establish a global function as a success listener attached to the success area
3
Establish a global function as a failure listener attached to the error area
Setting up the click handlers for the buttons is straightforward.
$('#goodButton').click(function(){
$.get('reflectData.jsp');
});
$('#badButton').click(function(){
$.get('returnError.jsp');
});
The good button is set up to initiate an Ajax request to a resource that will return a
success status, and the bad button initiates a request to a resource that always
returns an error status.
success status, and the bad button initiates a request to a resource that always
returns an error status.
Now we use the
ajaxSuccess()
command to establish a success listener
attached to the
<div>
element with the
id
of
successDisplay
as follows:
$('#successDisplay').ajaxSuccess(function(info){
$(info.target)
.append('<div>Success at '+new Date()+'</div>');
});