gpt4 book ai didi

javascript - 将我自己的回调与 HttpRequest 对象结合使用

转载 作者:行者123 更新时间:2023-11-28 02:59:19 25 4
gpt4 key购买 nike

我正在编写一个不使用库的 Http 请求(另一个脚本存在冲突...)

但是我在对象的范围方面遇到了麻烦。下面是调用脚本,然后是 Ajax_Request 对象。

function loadCard(e) {
var element = e.target;
if($('overlay')) {
return false; //something is already over the layout
}

var card = '/card/'+element.id;
var option = {method:'post', parameters:'test', async:true}

loadOverlay();
var ajax = new Ajax_Request(card, option);

}

//Ajax_Request

function Ajax_Request(url, options) {

if(typeof url !== 'undefined') {
this.url = url;
}

if(typeof options.method !== 'undefined') {
this.method = options.method;
} else {
this.method = 'get';
}

if(typeof options.parameters !== 'undefined') {
this.parameters = options.parameters;
}

if(typeof options.async !== 'undefined') {
this.async = true;
} else {
this.async = false;
}

if(window.XMLHttpRequest) {
this.request = new XMLHttpRequest();
} //check for MS browser

this.makeRequest = function() {
try {
this.request.onreadystatechange = this.checkReadyState;
this.request.open(this.method, this.url, this.async);
if(this.method == 'post') {
this.request.send(this.parameters);
} else {
this.request.send(null);
}
} catch(err) {
alert(err);
}
}

this.setResponse = function(r) {
alert(r)
this.response = r;
}

this.getResponse = function() {
return this.responseText;
}


this.checkReadyState = function(r) {
switch(this.readyState) {
case 4:
//Represents a "loaded" state in which the response has been completely received.
if(this.status == 200) {
this.setResponse(this.responseText)
}

...

}

}
}

我正在尝试设置对属性的响应,以便我的调用对象可以使用它。但是当我尝试调用 this.setResponse() 时,我收到一个错误,指出它未定义。如何将 onreadystatechange 回调正确绑定(bind)到我的程序?

脚本否则会正确返回数据,我可以简单地在那里输出它,但我需要更多的灵 active 。

谢谢丰富

最佳答案

这发生在您身上,因为在 checkReadyState 函数中 this 实际上代表 XMLHttPRequest 实例而不是您的 Ajax_Request 对象,因此 this.setResponse 是不明确的。为了引用你的对象的方法,你必须使用一个小技巧:var that = this

function Ajax_Request(url, options) {
var that = this;

...

this.checkReadyState = function (r) {
switch(this.readyState) {
case 4:
if(this.status == 200) {
// "this" refers to the XMLHttpRequest,
// but "that" refers your custom Ajax object
that.setResponse(this.responseText)
}

...
}
}
}

关于javascript - 将我自己的回调与 HttpRequest 对象结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1557198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com