如下代码中,为什么在ajax的构造函数中,this.XX值变成未定义了呢?

<title>构造函数</title>
<script>
$ = document.getElementById;
function news() {
this.divid = "";

this.get = function(divid) {
xmlHttp = this.GetXmlHttpObject();
if (xmlHttp==null) {
alert ("您的浏览器不支持AJAX!");
return;
}
this.divid = divid;
//this.get_Changed();
var url = "news.php";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange=this.get_Changed;
xmlHttp.send(null);
},

this.get_Changed = function() {
if (xmlHttp.readyState==4) {
str = xmlHttp.responseText;
$(this.divid).innerHTML = str;
alert(this.divid) //为什么this.divid 为undefine呢
}
}

this.GetXmlHttpObject = function() {
var xmlHttp=null;
try { // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) { // Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

}

var News = new news();
News.get("aa"); //在aa中加载news.php的内容

</script>

</head>

<body>
<div id="aa"></div>
</body>
已经解决了,确实是作用域的问题,谢谢抛砖引玉
用_this就搞定了
function news() {
var _this = this;
this.divid = "";

this.get = function(divid) {
……
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange=this.get_Changed;
xmlHttp.send(null);
},

this.get_Changed = function() {
if (xmlHttp.readyState==4) {
str = xmlHttp.responseText;
$(_this.divid).innerHTML = str;
alert(_this.divid);
}
}
}

幕布斯7119047
浏览 137回答 1
1回答

交互式爱情

回调的时候作用域已经变了,this好像变成xmlHttp这个还是什么忘掉了,你调试一下就知道了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
JQuery