Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I switch easily between an Ajax-based website and a basic HTML website?

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:

  • What is the best way to achieve this goal easily?
  • Should I design two views for each page?

I use jQuery and JSON as the result of this answer.

like image 631
Abdullah Avatar asked Dec 17 '22 01:12

Abdullah


1 Answers

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.

like image 179
BalusC Avatar answered Feb 15 '23 22:02

BalusC