gpt4 book ai didi

javascript - 如何在另一个函数中使用来自ajax的回调函数

转载 作者:行者123 更新时间:2023-11-30 15:49:59 25 4
gpt4 key购买 nike

如何在另一个函数中使用ajax的回调函数

我有 ajax 功能:

function correct_date(raw_date){ 
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
showTheValue(result);
}
});
}

var showTheValue = function(correct_day_value) {
console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
return correct_day_value;
};

我想在另一个类似的函数中获得来自 ajax 的响应/数据值:

function correct_start_date() {
document.getElementsByTagName("INPUT")[1].value = showTheValue();
}

如何在另一个函数中使用来自 ajax 的响应数据?

最佳答案

您可以使用 JavaScript Promise。

http://www.html5rocks.com/en/tutorials/es6/promises/

function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);

req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};

// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};

// Make the request
req.send();
});
}

关于javascript - 如何在另一个函数中使用来自ajax的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39526280/

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