[英]Two callback functions are being executed in custom AJAX function
I have created a custom GET
and POST
function in javascript to handle my AJAX requests. 我已经在javascript中创建了自定义的GET
和POST
函数来处理我的AJAX请求。 When I try to make a call, fail
callback is executed first and then the done
callback. 当我尝试拨打电话时,首先执行fail
回调,然后执行done
回调。 The response from AJAX is a valid JSON string and I do not understand why this is happening. 来自AJAX的响应是有效的JSON字符串,我不明白为什么会这样。 Only done
callback must be executed if the response is valid JSON. 如果响应是有效的JSON,则仅必须执行done
回调。
get('ajax/autocomplete.php', {q: q}, function(data) {
//done, executed second
}, aww());//Error, executed first
function get() {
var data,
done,
fail,
done_index = null,
str = '',
ajax = new XMLHttpRequest(),
url = arguments[0];
for(var i=0; i<arguments.length; i++) {
if(typeof arguments[i] == 'object') {
data = arguments[i];
for(var key in data) {
if(str != "") str += "&";
str += key + "=" + encodeURIComponent(data[key]);
}
if(str != '') url += '?';
} else if(typeof arguments[i] == 'function') {
if(!done_index) {
done = arguments[i];
done_index = i;
}
if(i != done_index) {
fail = arguments[i];
}
}
}
ajax.onreadystatechange = function() {
console.log(ajax.readyState, ajax.status);
if(ajax.readyState === XMLHttpRequest.DONE && ajax.status === 200) {
var response = ajax.responseText;//treat empty response as valid JSON
if(response.length == 0) response = '""';
try {
var json = JSON.parse(response);
return (done) ? done(json) : false;
} catch(e) {
console.log(e);
return (fail) ? fail() : false;
}
}
};
ajax.open('get', url + str);
ajax.send();
}
You're calling the aww()
function in the argument list to get()
, because you have parentheses after it. 您正在参数列表中将aww()
函数调用为get()
,因为其后带有括号。 You should just pass a reference to the function. 您应该只传递对该函数的引用。 It should be: 它应该是:
get('ajax/autocomplete.php', {q: q}, function(data) {
}, aww);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.