通过使用Promise或回调函数,确保异步Ajax函数正确返回数据并处理它。
以下是使用Promise解决的示例代码:
function ajaxFunction(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
ajaxFunction('https://jsonplaceholder.typicode.com/todos/1')
.then(function (response) {
console.log('成功:', response);
})
.catch(function (error) {
console.log('错误:', error);
});
如果要使用回调函数,可以使用以下示例代码:
function ajaxFunction(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
callback(xhr.responseText);
};
xhr.send();
}
ajaxFunction('https://jsonplaceholder.typicode.com/todos/1', function (response) {
console.log(response);
});
下一篇:Ajax函数未被执行。