我正在創建完全基於Ajax的網站,所以所有操作都調用不同的JS函數,因此我在每個函數中都使用這個Ajax代碼,這使得我的函數成爲一個大代碼。縮短Ajax代碼
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var getData=xmlhttp.responseText;
if(getData=="something") {
/*
code goes here
*/
}
else {
/*
code goes here
*/
}
}
}
xmlhttp.open("GET","mypage.php",true);
xmlhttp.send();
所以我想問問我應該使用只包含上面的Ajax代碼不同的功能,並宣佈我的變量全球的getData所以每當我需要它,我應該稱呼它。
這裏是我想用
var getData=""; /*declaring var Globally (I read it like this dont know right)*/
function oneAjax(checkPage) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
getData=xmlhttp.responseText;
/*now check further in the function which called it*/
}
}
xmlhttp.open("GET",checkPage+".php",true);
xmlhttp.send();
}
它會創建與其他正在運行的行爲有關的任何衝突? 或爲我的問題提供任何正確的解決方案。
也許提供一個應如何調用oneAjax的例子。我認爲回調可能會讓初學者感到困惑。教程中的 –