You need Unobtrusive Javascript, which is part of Progressive Enhancement.
First, start creating a fully functional webapplication without any line of Javascript. Once you got it to work, then start writing Javascript code which "takes over" the raw HTML work without changing any line of HTML/CSS. In the server side code you need to add logic which recognizes whether the request has been fired by JavaScript or not and return response accordingly. You can test both cases by en/disabling JavaScript in the webbrowser. In Firefox it's easy with Web Developer Toolbar.
For example, you have a list of mails with all HTML links which should show the mail body:
<a href="mail/show/1" class="show">Message title</a>
Without JavaScript, this would fire a HTTP request to the servlet which loads the mail identified by 1
, forwards the request to a JSP which hides the message list in the view and shows the mail in the view.
With JavaScript/jQuery, you need to write code which does exactly the same with help of Ajax, e.g.:
$('a.show').click(function() {
$.getJSON(this.href, callbackFunctionWhichHidesListAndShowsMail);
return false;
});
In the server side you have to distinguish between normal requests and ajax requests so that you can return response accordingly.
boolean ajax = "XMLHttpRequest".equals(request.getHeader("x-requested-with"));
// ...
if (ajax) {
writeJson(response, mail);
} else {
request.setAttribute("mail", mail);
request.getRequestDispatcher("/WEB-INF/mail.jsp").forward(request, response);
}
Finally, to give the user an option to switch between the modes manually, you have to set a cookie or preferably (since cookies are disableable) pass some information in URL (pathinfo or request parameter) which forces the server to disable emitting the <script>
lines.