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

标签 javascript jquery ajax

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

相关文章:

javascript - 我希望倒数计时器在计时器达到 0 后重定向到 url

jquery - 从本地文件加载时数据表抛出 "invalid JSON"错误

javascript - 如何让网页上的图片自动刷新

Javascript event.stopPropagation() 不适用于 `accesskey` 属性

javascript - 前端集成测试

ajax - AJAX 是如何实现的,它如何帮助 Web 开发?

jQuery 数据表 Twitter/facebook 风格分页

javascript - 使用 api 检查文件是否在 Chrome 中下载

JavaScript:一段时间后更改 Div 背景

javascript - jQuery 数组显示分隔逗号