如何在另一个函数中使用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。
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/