我想自动刷新网页的一部分而不刷新整个页面。 (比如网页的一个部门)。
我有一个定期调用PHP页面的脚本。
脚本:
<!----------- ********* AJAX code to auto refresh the part of a webpage************ --------->
<script langauge="javascript">
function loadXmlHttp(url, id) {
var f = this;
if (loadXmlHttp.xmlHttp){
f.xmlHttp = loadXmlHttp.xmlHttp();
f.el = document.getElementById(id);
f.xmlHttp.open("GET", url, true);
f.xmlHttp.onreadystatechange = function(){f.stateChanged();};
f.xmlHttp.send(null);
} else {
alert('Your browser does not support AJAX!');
}
}
loadXmlHttp.xmlHttp = null;
loadXmlHttp.re = /^http/.test(window.location.href);
/*@cc_on @*/ // used here and below, limits try/catch to those IE browsers that both benefit from and support it
/*@if(@_jscript_version >= 5) // prevents errors in old browsers that barf on try/catch & problems in IE if Active X disabled
try {loadXmlHttp.ie = window.ActiveXObject}catch(e){};
end @*/
if (window.XMLHttpRequest && (!loadXmlHttp.ie || loadXmlHttp.re))
loadXmlHttp.xmlHttp = function(){return new XMLHttpRequest();}; // Firefox, Opera 8.0+, Safari, others, IE 7+ when live - this is the standard method
else if (/(object)|(function)/.test(typeof createRequest))
loadXmlHttp.xmlHttp = createRequest; // ICEBrowser, perhaps others
else {
loadXmlHttp.xmlHttp = null;
// Internet Explorer 5 to 6, includes IE 7+ when local //
/*@if(@_jscript_version >= 5)
try{loadXmlHttp.xmlHttp = function(){return new ActiveXObject("Msxml2.XMLHTTP");};}
catch(e){try{loadXmlHttp.xmlHttp = function(){return new ActiveXObject("Microsoft.XMLHTTP");};}catch(e){}}
@end @*/
}
loadXmlHttp.prototype.stateChanged = function(){
if (this.xmlHttp.readyState == 4 && (this.xmlHttp.status == 200 || !loadXmlHttp.re)){
this.el.innerHTML = this.xmlHttp.responseText;
if(this.success){
this.success();
}
}
}
</script>
<!----------- ********* AJAX code to auto refresh the part of a webpage ends here************ --------->
我称这个函数的Div是这样的:
<div class="textad" id="text"></div>
<script type="text/javascript">
(function(){
var statsrequest = new loadXmlHttp('display_text_ad.php', 'text'), repeat = arguments.callee;
statsrequest.success = function(){setTimeout(repeat, 6000);};
})();
</script>
</div>
现在,此代码适用于除Internet Explorer之外的所有浏览器。 (我检查过Chrome,Mozilla,Opera和Safari)。所以,我需要一点帮助修复Internet Explorer的这个bug。任何帮助将不胜感激。提前谢谢。
答案 0 :(得分:2)
问题是您的初始IE条件编译脚本缺少“@”字符。 end @*/
行应改为@end @*/
。
但是,应该指出,使用JScript版本的浏览器检测是not a good practice。一种更简单,更健壮的方法是直接测试您要使用的标准,并回退到旧版浏览器的变通方法。例如:
if (window.XMLHttpRequest) {
// Use native XHR object for modern browsers
loadXmlHttp.xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// Use the ActiveX control for legacy browsers
loadXmlHttp.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
// No XHR mechanism is available.
}