我正在尝试创建一个将对象作为参数的函数,并且在对象内部我想要一个对象方法,就像jQuery ajax一样。我现在的问题是我无法使用该对象方法。
function myAjax({
type,
url,
success
}) {
var suc = "";
typeof type === "undefined" ? type = "GET" : type = type;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
suc = this.responseText;
//alert(this.responseText);
}
};
req.open(type, url, false);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded ");
req.send("fname=chijioke&lname=francis");
function success(suc) {}
}
myAjax({
type: "post",
url: "page.html",
success: function(e) {
alert(e);
}
});
我想做与此jQuery ajax调用类似的事情
$.ajax({
type: "post",
url: "index",
data: {
id: id
},
success: function(feedback) {
alert(feedback);
}
});
我需要通过成功函数获取responseText
,但是它不起作用。我希望它能像jQuery ajax成功一样工作,这确实是出于学习目的。
答案 0 :(得分:3)
您要尝试的操作称为回调函数。而不是在函数内部声明一个函数,而是应该调用传递给它的函数。
所以而不是
function success(suc) {}
尝试做
success(suc);
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced这是我在该主题上找到的指南。
答案 1 :(得分:2)
您实际上想做的很普遍-回调函数。您将函数作为参数传递,并在内部简单地调用它。
在您的实现中,您正在做
function success(suc){}
这实际上只是定义了一个称为成功的方法。您实际上需要像这样调用该方法
success(suc);
此外,检查类型是否未定义的行通常不会评估为true,因为您应该检查
type === undefined //"undefined" != undefined
我还要提到的一件事是,您正在尝试在方法末尾调用回调函数,但实际上您应该在onreadystatechange中调用它,以便在请求完成时调用它,方法完成后不会。
req.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
suc = this.responseText;
success(suc);
}
};
答案 2 :(得分:1)
执行myAjax时已经声明了“成功”方法,因此无需在myAjax中再次声明。
尝试一下:
function myAjax(type, url, success) {
var suc = "";
typeof type === "undefined" ? type = "GET" : type = type;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
suc = this.responseText;
success(suc); //Call to outside method
}
};
req.open(type, url, false);
req.setRequestHeader("Content-type", "application/x-www-form-
urlencoded ");
req.send("fname=chijioke&lname=francis");
}