I have a website ( based on JSP/Servlets, using the MVC pattern), and I want to support Ajax-based website and basic HTML-based website. website visitors should be able to change the surfing mode from Ajax to basic HTML and vice versa, - as it applies in Google-mail.
The questions:
I use jQuery and JSON as the result of this answer.
You need Unobtrusive JavaScript, which is part of progressive enhancement.
First, start creating a fully functional web application 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 web browser. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With