出于工作和学习的需要,参考《Ajax in Action》一书,自写了一个较通用的Ajax处理类:AjaxObject。通过创建一个AjaxObject实例,调用其方法:
sendRequest();
就可以实现对服务器的异步请求和响应,而且不受全局变量的限制。
其代码如下:
查看代码 JAVASCRIPT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | /* * define a javascript class, this is its constructor. * For using this class object, make sure define an outer Ajax Component(may be an object) "ajaxComponent", * which must has two methods: handleMessage(req) and handleError(req), * for responsing handling successful message and error message. */ AjaxObject = function(ajaxComponent, url, method){ this.ajaxComponent = ajaxComponent; this.url = url; this.method = method ? method : "POST"; //default use "post" method } AjaxObject.prototype = { sendRequest: function() { var req = this.initReqInstance(); if(req){ var oThis = this; //must declare a local reference to 'this' for closure req.onreadystatechange = function(){ //appoint callback function oThis.handleResponse(req); }; try { req.open(this.method, this.url, true); req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } catch (e) { alert(e); } req.send(null); } }, //!Notice: shound be separated by ',' initReqInstance: function(req){ var req; if(window.XMLHttpRequest) { // Non-IE browsers req = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE browsers try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (err) { req = new ActiveXObject("Microsoft.XMLHTTP"); } } return req; }, //!Notice: shound be separated by ',' handleResponse: function(req){ if (req.readyState == 4) { // Complete if (req.status == 200) { // OK response this.ajaxComponent.handleMessage(req); } else { // Error handling this.ajaxComponent.handleError(req); } } } //the last key:value pair should not have ',' }; |
测试函数如下:
查看代码 JAVASCRIPT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /*test function*/ function test() { //new a ajax helper object for ajax component var ajaxComponent = new Object(); ajaxComponent.handleMessage = function(req){ //here can't use prototype way because ajaxComponent has been a "new" object. alert("req is OK: " + req.status); }; ajaxComponent.handleError = function(req){ alert("Problem: " + req.statusText); }; var url = "test.do?cmd=testAjax"; var ao = new AjaxObject(ajaxComponent, url); ao.sendRequest(); } |
注意:
1、要使用AjaxObject类,必须在外部定义一个“组件”,该组件可以是一个DOM对象,也可以一个普通的Ojbect对象,但这个组件必须包含两个函数:
handleMessage(req)和handleError(req),分别处理ajax成功返回后的响应和失败返回后的响应。
2、AjaxObject的构造函数的只有前两个参数(ajaxComponent和url)是必须的,第三个(method)是可选的。
3、使用测试函数时,要将url变量的值置换成具体环境真实的值。