肥嘟嘟(Fatbobman)的学习笔记Rss Feed

上学的时候懒不愿意做笔记,但确实了解笔记的重要性。现在想做笔记了,但是还是懒,当然对于重要性的认识丝毫没有动摇。

2005/10/17

使用rico实现ajax应用的例子(1)

  关于ajax是什么已经有很多方面的介绍了。本着拿来主义的原则,选择了rico这个纯js解决方案后端配合karrigell来实现一些ajax应用。
  rico 的ajaxEngine 有多种获取、处理数据的方式。其中通过直接将xml数据与element相绑定可能是最简单的一种。
  rico中实现ajax应用通常需要分3步走:
  1. Register the Ajax request handler. This tells the AjaxEngine that a specific
    web service or server call is mapped to a request handler name.
  2. Register the Ajax response handler. This is either specifies an HTML element
    as the target of the data being returned (in which case the contents of the
    response is HTML code) or it specifies a specific JavaScript object that will
    manage the response
  3. Invoke the Ajax request when the appropriate event occurs in the interface.

  通过一个实际的例子来演示。

  客户端 ajaxtest.html

<html>
<head>
<title>AjaxTest</title>
//这两个文件是rico实现任何功能的基础,必须要有:)
<script src="/jsscripts/prototype.js"></script>
<script src="/jsscripts/rico.js"></script>
<script>
var onloads = new Array();
function bodyOnLoad() {
for ( var i = 0 ; i < onloads.length ; i++ )
onloads[i]();
}
</script>
</head>
<body onload="javascript:bodyOnLoad()">
<script>
//要在onload时完成所要注册的request、ajaxelement等物件。这个问题最初困扰了我好几个小时。
onloads.push( registerAjaxStuff );
function registerAjaxStuff()
{
//注册一个request,命名为getwords,后端处理程序为 ajaxresponse.py。如果你后端不想通过动态语言处理的话,也可以直接使用xml文件。
ajaxEngine.registerRequest('getwords','ajaxresponse.py');
//注册一个客户端显示的element, id='word' ,必须在html里面有。
ajaxEngine.registerAjaxElement('word');
}
function getword()
{
//获取数据、自动完成更新。可以调用参数,如下结构:ajaxEngine.sendRequest('getPersonInfo',"firstName=" + firstName,"lastName=" + lastName );
ajaxEngine.sendRequest('getwords');
}
</script>
<div id="word">This is a test</div>
//实际运行时会将后端获取的数据替换掉div word中的内容。后端数据可以直接包含html、css等元素,这样可以连版式调整问题一并解决。

<div ><a href="javascript:getword();">Click Here</a></div>
</body>
</html>

  服务端程序 ajaxresponse.py
import random
RESPONSE['Content-Type'] = 'text/xml'
RESPONSE['Cache-Control']='no-store' #解决ie下刷新问题

print """<?xml version="1.0" ?>
<ajax-response>
<response type="element" id="word">
<b>hello world
"""
print str(random.random())
print """</b>
</response>
</ajax-response>
"""


  后端程序生成的xml数据类似如下:
<ajax-response> <response type="element" id="word"> <b>hello world 0.208002263747</b> </response> </ajax-response>


  数据必须包含<ajax-response>.这点可能正是rico 灵活性方面的弱势吧,只能接受其规定格式的xml数据。
  每个被绑定的element 都需要一个response 返回数据。可以在程序中使用registerAjaxElement绑定多个element,每个对应xml数据中相对应id的<response>.

  这是一个很简单的例子来感受ajax所带来的变化,以及rico实现上的便捷。

0 Comments:

发表评论

<< Home