switch ajax,How to switch easily between ajax-based website an

本文探讨了渐进增强的概念,首先创建一个不依赖JavaScript的全功能Web应用,然后通过Ajax逐步增强用户体验。在服务器端,根据请求是否来自JavaScript来调整响应。以邮件列表为例,解释了如何使用jQuery实现点击链接展示邮件内容,同时提供了让用户手动切换模式的选项。
摘要由CSDN通过智能技术生成

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:

Message title

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 lines.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值