Sun的Java BluePrints上梅兰竹菊四个例子 ,示范了Ajax的标准用法--Refreshing Data 、Realtime Form Validation 、Auto-completion 、Progress Bar ,俱是Ajax最主要的应用。 不过Blue Prints只示范了标准的做法。而Rails则很变态的自己做了一个面向对象的JavaScript库--Prototype。对Ajax的封装就是在这上面作的,还比Blue Prints多了一点点想象力,提供了多一点点的扩展。 但是可封装的代码不是很多,OO带来的重用优势不很明显,而OO的javascript又太难看懂,所以准备参考它的做法,改成普通的javascript形式。 Java BluePrints里的标准Java Script:
<script type="text/javascript"> var req; //全局的xmlhttp对象
//初始化XMLHttp对象,兼容IE和Firefox function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } }
//执行远程访问的主函数 function checkForMessage() { var url = "foo.do"; initRequest(); req.onreadystatechange = processReqChange; //注册CallBack函数 req.open("GET", url, true); } //远程访问结束之后的处理函数 function processReqChange() { if (req.readyState == 4) { if (req.status == 200) { var item = req.responseXML.getElementsByTagName("message")[0]; window.document.getElementById("td1").innerText = item; } else { window.status = "No Update "; } } }
老郁抱怨说几乎没有封装,其实要封装也容易,把checkForMessage()改为接受url和callback funcion函数指针这两个参数的通用函数,和initRequest()一起放进公共文件后,页面里就不需要再写xmlhttp有关的东西,只专心写call back处理函数了,但这样子也没省几行代码嘛。 其实,Ajax里面最重要的部分是分析responseXML并加以应用的函数,Blue Prints里面的代码还是挺值得参考的。 如果能把这个处理也根据这有数的几种应用封装就好了,但这个好像全世界都没有什么想象力。Rails好像有一点,但也只是一点。
Rails的封装 1.OO的JavaScript库--Prototype Rails闲着没事,自己做了一个面向对象的JavaScript库--Prototype, 实在太变态了. 而且通过JavaScript Helper Taglib作了进一步封装,如下:(为方便阅读,对代码稍有简化)
//远程后访问foo.do,完成后调用processReqChange
<%= link_to_remote :complete => "processReqChange(request)", :url => {"foo.do"} %>
而页面实际生成的代码是这样的,:
<a onclick="new Ajax.Request('list.do', {onComplete:function(request){processReqChange(request)}"/>
2. 那点更多的想象力 他的一点想象力就是能够自动把某个element的innerHtml update成responseText 使用link_to_remote tag的写法,完成后直接把responseText更改myDiv的inner Text: <%= link_to_remote :update => "myDiv", :url => {"foo.do" } %>
实际的页面代码:
<a onclick="new Ajax.Updater('myDIv', 'foo.do);"/>
3.更多的事件注册 除了Complete事件,Rails还支持你注册loading和interactive事件。
4.Form的不刷新页面的透明提交 Rails还提供form_remote_tag的封装,代码如下: <%=form_remote_tag :url =>{ "foo.do"}%>
实际生成的JavaScript:
<form onsubmit="new Ajax.Request('foo.do', {parameters:Form.serialize(this)});"> 默认把form的所有input框都提交了. 5.最后,奇文共欣赏,疑义相与析, 这个可爱的 OO的可继承的javascpit 库 (可惜作者说没有一个好的工具能帮它注释这种OO型的代码并生成JSDoc,也就没写文档了)
var Ajax = { getTransport: function() { return Try.these( function() {return new ActiveXObject('Msxml2.XMLHTTP')}, function() {return new ActiveXObject('Microsoft.XMLHTTP')}, function() {return new XMLHttpRequest()} ) || false; }, emptyFunction: function() {} } Ajax.Base = function() {}; Ajax.Base.prototype = { setOptions: function(options) { this.options = { method: 'post', asynchronous: true, parameters: '' }.extend(options || {}); } } Ajax.Request = Class.create(); Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; Ajax.Request.prototype = (new Ajax.Base()).extend({ initialize: function(url, options) { this.transport = Ajax.getTransport(); this.setOptions(options); try { if (this.options.method == 'get') url += '?' + this.options.parameters + '&_='; this.transport.open(this.options.method, url, true); if (this.options.asynchronous) { this.transport.onreadystatechange = this.onStateChange.bind(this); setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10); } this.transport.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); this.transport.setRequestHeader('X-Prototype-Version', Prototype.Version); if (this.options.method == 'post') { this.transport.setRequestHeader('Connection', 'close'); this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } this.transport.send(this.options.method == 'post' ? this.options.parameters + '&_=' : null); } catch (e) { } }, onStateChange: function() { var readyState = this.transport.readyState; if (readyState != 1) this.respondToReadyState(this.transport.readyState); }, respondToReadyState: function(readyState) { var event = Ajax.Request.Events[readyState]; (this.options['on' + event] || Ajax.emptyFunction)(this.transport); } }); Ajax.Updater = Class.create(); Ajax.Updater.prototype = (new Ajax.Base()).extend({ initialize: function(container, url, options) { this.container = $(container); this.setOptions(options); if (this.options.asynchronous) { this.onComplete = this.options.onComplete; this.options.onComplete = this.updateContent.bind(this); } this.request = new Ajax.Request(url, this.options); if (!this.options.asynchronous) this.updateContent(); }, updateContent: function() { if (this.options.insertion) { new this.options.insertion(this.container, this.request.transport.responseText); } else { this.container.innerHTML = this.request.transport.responseText; } if (this.onComplete) { setTimeout((function() {this.onComplete(this.request)}).bind(this), 10); } } }); 
|