今天在调试程序的时候发现了一个奇怪的问题,我写了一个封装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 };
但是始终无法调用到onOk这个函数,即使服务器端返回了正确的结果,始终调用不到onOk这个函数,后来发现。。。
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 };
加上this关键字就可以调用到了,我很纳闷,为什么不添加this关键字,为什么就调用不到onOk这个函数呢?
原来在onOk所在函数和外部都没有这个responseText变量,只有指定了this,才能准确定位到XMLHTTPRequest对象中的属性