【问题标题】:How to effectively chain 3 ajax calls where One ajax call feeds the other Two ajax calls?如何有效地链接 3 个 ajax 调用,其中一个 ajax 调用提供其他两个 ajax 调用?
【发布时间】:2019-08-27 00:42:45
【问题描述】:

我正在尝试找到链接 3 个 ajax 调用的有效方法,其中一个 ajax 调用馈送其他两个 ajax 调用。 这是扫描仪:


//Invoke the ajax calls
firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax).done(function(second_ajax_data, third_ajax-data) {
        console.log(second_ajax_data);
        console.log(third_ajax-data);
});

//Define our ajax calls

const firstAjax = function(urlAjax, userName) {

      return $.ajax({
              url: urlAjax,
              type: 'POST',
              data: userName
             )};

const secondAjax = function(sessionId) {

       return $.ajax({
              url: '/userLogins/getUserLogins',
              type: 'POST',
              data: sessionId
             )};

const thirdAjax = function(sessionId) {

       return $.ajax({
              url: '/userHistory/getUserHistory',
              type: 'POST',
              data: sessionId
             )};

基本上,firstAjax 调用检索 sessionId,然后将其同时提供给其他 2 个 ajax 调用。通过上面的实现,我无法获得最后两个调用返回的数据。 我会很感激任何帮助

【问题讨论】:

    标签: javascript ajax promise


    【解决方案1】:

    我认为这样的事情可能会奏效:

    function send_ajax_request(data){
        $.ajax({
          url: "yoururl",
          type: "GET",
          dataType: "json",
          data: {
            data: data,
            csrfmiddlewaretoken: '{{ csrf_token }}'
          },
          success: function (json) {
            next_ajax(json['success']);
    
          },
          error: function (xhr, errmsg, err) {
            alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
          }
        });
    

    }

    function next_ajax(data){
    $.ajax({
        url: "yoururl",
        type: "GET",
        dataType: "json",
        data: {
          coord: JSON.stringify({ "info": data[0], "info2": data[1] }),
          csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        success: function (json) {
          console.log(json)
    
        },
        error: function (xhr, errmsg, err) {
          alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
        }
      });
    

    }

    基本上,使用 Ajax 的 sucess 函数来调用下一个 Ajax 请求。应该可以!

    【讨论】:

    • 您的方法涉及嵌套,如果您有多个 ajax 调用,这可能会变得很难看。感谢您的反馈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    相关资源
    最近更新 更多