我正在创建完全基于 Ajax 的网站,因此所有操作都会调用不同的 JS 函数,因此我在我的每个函数中都使用了这个 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();
}
会不会和其他正在运行的 Action 产生冲突? 或为我的问题提供任何正确的解决方案。
最佳答案
如果您不打算使用现成的库,您应该将“回调”传递给 oneAjax
:
function oneAjax(checkPage, done, fail) {
...
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
done(xmlhttp.responseText, xmlhttp.status);
} else {
fail(xmlhttp.status);
}
}
};
}
调整传递给回调的参数以满足您的要求。
使用:
oneAjax('mypage', function(text, status) {
// success
console.log(status);
}, function(status) {
// failure
console.log(status);
});
关于javascript - 缩短 Ajax 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16915813/