在 jQuery 中,当某些东西正在加载时我可以这样做:
$.ajax({
url: "/answer_checker.php",
global: false, type: "POST",
data: ({...clipped...}),
cache: false,
beforeSend: function() {
$('#response').html("<img src='/images/loading.gif' />");
},
success: function(html) {
$('#response').html(html);
}
}
如何在纯 javascript 中应用 beforeSend 和 success?我目前有这个:
function processGeneric() {
setTimeout(function () {
if (xmlHttpObject.readyState === 0 || xmlHttpObject.readyState === 4) {
xmlHttpObject.open("GET", requestLink, true);
xmlHttpObject.onreadystatechange = function () {//some code to handle here};
xmlHttpObject.send(null);
}
}, timeout);
}
最佳答案
您创建一个函数来接受您想要的回调以及其他 ajax 选项,然后具有该函数:
调用“发送前”回调
进行 ajax 调用,which is well-covered in this other question and its answers
调用完成后,调用完成回调
大致是这样的:
function processGeneric(url, beforeSend, completion) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadstatechange = function() {
if (xhr.readyState === 0 || xhr.readyState === 4) {
if (completion) {
completion(xhr);
}
done();
}
};
xhr.open("GET", url, true);
if (beforeSend) {
if (beforeSend(xhr) === false) {
done();
return;
}
}
xhr.send(null);
return xhr;
function done() {
xhr.onreadystatechange = null;
xhr = undefined;
}
}
关于javascript - 普通 javascript beforeSend 和成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29164049/