首先声明,我是一个菜鸟。一下文章中出现技术误导情况盖不负责
今天在调试程序的时候现发了一个奇异的题问,我写了一个封装ajax的对象,名字就叫ajax:
1 var ajax = { 2 get : function(url, onOk) { 3 var xmlHttpRequest = this.createXMLHttpRequest(); 4 xmlHttpRequest.open("GET", url, true); 5 xmlHttpRequest.onreadystatechange = function() { 6 if (this.readyState == 4) { 7 if (this.status == 200) { 8 onOk(responseText); 9 } else { 10 onOk("异步通信失败"); 11 } 12 } 13 }; 14 xmlHttpRequest.send(null); 15 }, 16 post : function(url, param, onOk) { 17 var xmlHttpRequest = this.createXMLHttpRequest(); 18 xmlHttpRequest.open("POST", url, true); 19 xmlHttpRequest.onreadystatechange = function() { 20 if (this.readyState == 4) { 21 if (this.status == 200) { 22 onOk(responseText); 23 } else { 24 onOk("异步通信失败"); 25 } 26 } 27 }; 28 xmlHttpRequest.send(param); 29 }, 30 createXMLHttpRequest : function() { 31 if (window.XMLHttpRequest) { 32 return new XMLHttpRequest(); 33 } else if (window.ActiveXObject) { 34 return new ActiveXObject("Microsoft.XMLHTTP"); 35 } 36 } 37 };
1 var ajax = { 2 get : function(url, onOk) { 3 var xmlHttpRequest = this.createXMLHttpRequest(); 4 xmlHttpRequest.open("GET", url, true); 5 xmlHttpRequest.onreadystatechange = function() { 6 if (this.readyState == 4) { 7 if (this.status == 200) { 8 onOk(this.responseText); 9 } else { 10 onOk("异步通信失败"); 11 } 12 } 13 }; 14 xmlHttpRequest.send(null); 15 }, 16 post : function(url, param, onOk) { 17 var xmlHttpRequest = this.createXMLHttpRequest(); 18 xmlHttpRequest.open("POST", url, true); 19 xmlHttpRequest.onreadystatechange = function() { 20 if (this.readyState == 4) { 21 if (this.status == 200) { 22 onOk(this.responseText); 23 } else { 24 onOk("异步通信失败"); 25 } 26 } 27 }; 28 xmlHttpRequest.send(param); 29 }, 30 createXMLHttpRequest : function() { 31 if (window.XMLHttpRequest) { 32 return new XMLHttpRequest(); 33 } else if (window.ActiveXObject) { 34 return new ActiveXObject("Microsoft.XMLHTTP"); 35 } 36 } 37 };
来原在onOk在所函数和外部都没有这个responseText变量,只有指定了this,才能精确位定到XMLHTTPRequest对象中的属性
文章结束给大家分享下程序员的一些笑话语录: 这个世界上只有10种人:懂得二进制的和不懂得二进制的。