是否有一种方法可以在回调xmlHttpReq.onreadystatechange中更改文档的全局变量
Is there a way to change a global variable on the document in the call back xmlHttpReq.onreadystatechange?
我对AJAX非常陌生,但是现在我想根据回调函数xmlHttpReq中更改的状态为文档的全局变量设置一些值。onreadystatechange,我使用了类似
的东西function checkFile(fileUrl) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
if(self.xmlHttpReq == null){
alert("Your browser does not support XMLHTTPReq")
}
self.xmlHttpReq.open('HEAD', fileUrl, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
if (self.xmlHttpReq.status == 200) {
window.rett = 1;
//alert(window.rett);
} else if (self.xmlHttpReq.status == 404) {
window.rett = 0;
//alert(window.rett);
}
}
}
self.xmlHttpReq.send();
}
和我使用的checkFile
在一个jquery模板像这样:
<script id="resultTemplate" type="text/x-jquery-tmpl">
<li> ${checkFile(link)} <b> {{if window.rett == 1 }} ${link} {{/if}}</b> </li>
</script>
但是当我访问Jquery模板中的window.rett
时,它说未定义…
我想获得全局值的原因是我想基于全局值生成不同的GUI。
也许这不是一个使用全局变量的好做法?任何建议都很感激。
很可能是因为当您尝试访问它时,AJAX请求尚未完成(尚未达到状态4),因此您的全局变量尚未声明(或者如果声明了,它仍然包含前一个结果的值)
我建议你在回调中使用你的模板。这样,当模板检查值时,值已经存在了:
function yourAjaxFunction(arg1, arg2,...,callback){
//all AJAX setup codes here
if (self.xmlHttpReq.readyState === 4) {
if (self.xmlHttpReq.status === 200) {
//sending the callback a 1
callback(1);
} else if (self.xmlHttpReq.status === 404) {
//sending the callback a 1
callback(0);
}
}
//AJAX send codes
}
//how you should use it
yourAjaxFunction(arg1,arg2,...,function(rett){
//use rett here
//parse template here
});
相关文章:
- 没有找到相关文章