如何基于ajax的网站和基本的HTML网页之间轻松切换? [英] How to switch easily between ajax-based website and basic HTML website?

查看:258
本文介绍了如何基于ajax的网站和基本的HTML网页之间轻松切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站(基于JSP / Servlet的,使用MVC模式),我想支持基于AJAX的网站和基本的基于HTML的网站。网站访问者应该能够从阿贾克斯改变上网方式,以基本的HTML,反之亦然, - 因为它适用于谷歌的邮件

I have a website ( based on JSP/Servlets ,using 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 vise versa, - as it applies in Google-mail.

的问题:

  • 什么是轻松实现这一目标的最佳方式是什么?
  • 如果我设计的两种观点的每一页?

我使用jQuery和JSON作为这样的结果<一个href="http://stackoverflow.com/questions/2589047/passing-data-from-a-servlet-to-javascript-$c$c-in-an-ajax-application">answer.

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

推荐答案

您需要非侵入式JavaScript ,这是逐步增强。

首先,开始创建一个全功能 web应用的没有的任何JavaScript的线。一旦你得到它的工作,然后开始编写JavaScript code的接管原始HTML工作的没有的改变HTML / CSS的任何行。在服务器端code,你需要的添加的逻辑,承认该请求是否已经被解雇或者通过JavaScript的不和返回相应的响应。您可以通过连接测试这两种情况下/禁用JavaScript中的网页浏览器。在Firefox中很容易与的Web开发工具栏

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.

例如,您有邮件的所有HTML链接列表,它应该显示邮件正文:

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>

没有JavaScript,这将触发一个HTTP请求到加载标识 1 邮件servlet时,转发它隐藏在视图中的邮件列表的请求到JSP并示出了邮件在视图中。

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.

使用的JavaScript / jQuery的,你需要写code这不正是在同阿贾克斯的帮助,例如:

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;
});

在服务器端,你有正常的请求和Ajax请求,这样就可以返回相应的响应区分开来。

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);
}

最后,为了给用户一个选项,手动模式之间进行切换,你必须pferably设置cookie或$ P $(因为饼干disableable)通过在URL的一些信息(PATHINFO或请求参数),这迫使服务器禁用发射&LT;脚本&GT;

这篇关于如何基于ajax的网站和基本的HTML网页之间轻松切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆