第二个ajax结果没有附加到我的div

问题描述 投票:0回答:5

我的函数有2个ajax请求。第二个ajax工作正常,但结果不会附加到我的div。这是我的代码。任何帮助,将不胜感激。

function load_candidates() {
  $.ajax({
    url: 'admin/requests/Get-Positions.php',
    method: 'POST',
    data: {
      id: id
    },
    dataType: 'json',
    success: function(result) {
      var textToInsert = '';

      $.each(result, function(key, value) {
        var position_id = value['id'];
        textToInsert += '<div class="card bg-primary text-center"><div class="card-body"><h4 class="text-white m-0" id="position">' + value['position'] + '</h4></div></div><br><div class="row">';
        $.ajax({
          url: 'admin/requests/Get-Candidate_Per_Position.php',
          method: 'POST',
          data: {
            position_id: position_id
          },
          dataType: 'json',
          success: function(data) {
            $.each(data, function(key, value) {
              textToInsert += '<div class="col-lg-4 col-sm-6 text-center mb-4"><h3>' + value['name'] + '</h3><p>' + value['candidate_number'] + '</p></div>';
            });
          }
        });
        textToInsert += '</div>';
      });
      $('#candidate_list').append(textToInsert);
    },
    error: function(xhr, status, error) {
      console.log(xhr.responseWithJSON)
    }
  });
}
javascript jquery ajax append
5个回答
0
投票

这是正确写入的第一个响应中每个()的输出:

  var textToInsert = '';

  $.each(result, function(key, value) {
    var position_id = value['id'];

    $.ajax({
      url: 'admin/requests/Get-Candidate_Per_Position.php',
      method: 'POST',
      data: {
        position_id: position_id
      },
      dataType: 'json',
      success: function(data) {
        textToInsert += '<div class="card bg-primary text-center"><div class="card-body"><h4 class="text-white m-0" id="position">' + value['position'] + '</h4></div></div><br><div class="row">';
        $.each(data, function(key, value) {
          textToInsert += '<div class="col-lg-4 col-sm-6 text-center mb-4"><h3>' + value['name'] + '</h3><p>' + value['candidate_number'] + '</p></div>';
        });
        textToInsert += '</div>';
        $('#candidate_list').html(textToInsert);
      }
    });
  });

0
投票

在ajax请求完成之前附加结果。这意味着TextToInsert在那一刻仍然是空的。它要么是async:false,要么将结果附加到ajax请求中


0
投票

感谢您回答并给我一点时间。这对我很有帮助。感谢你们。 .html(textToInsert)的诀窍。我不知道为什么。我对jquery有点新鲜。无论如何。感谢你们。我真的很感激。更多的权力


0
投票

这是一个使用async库的答案。当您必须执行一系列异步操作时,它非常有用。

要使用它,您必须在HTML代码中包含async.jsasync.min.js。您可以在CDNJS上找到脚本链接。

这里我只使用async.map()函数。这个想法是它为load_candidate数组中的每个项执行position_ids函数(第二个参数)。因此,所有AJAX请求都会同时被触发。但它等待所有这些完成,并将所有请求结果放入一个数组中。

我知道使用这种库可能看起来有点可怕,但老实说,如果你不得不做一些复杂的代码,有许多异步调用,有些取决于之前的结果,这值得研究。

我冒昧地将您的代码重构为更小,更具体的函数。我在浏览器中对它进行了测试并且它可以工作,只要记住你在调用id之前必须在某处定义你的load_candidates()变量。

function load_position(id, cbSuccess, cbError) {
  $.ajax({
    url: 'admin/requests/Get-Positions.php',
    method: 'POST',
    data: {
      id: id
    },
    dataType: 'json',
    success: cbSuccess,
    error: cbError
  });  
}

function load_candidate(position_id, callback) {
  $.ajax({
    url: 'admin/requests/Get-Candidate_Per_Position.php',
    method: 'POST',
    data: {
      position_id: position_id
    },
    dataType: 'json',
    success: function(result) {
      callback(null, result);
    },
    error: function(xhr, status, error) {
      callback(new Error('Error in 2nd request: ' + xhr.responseText));
    }
  });
}

function ajax_error_handler(xhr, status, error) {
  console.log(xhr.responseText);
}

function load_candidates(id) {

  // Fires the 1st request
  load_position(id, function(result1) {

    // This extracts all position ids from the result of 1st request
    var position_ids = result1.map(function(value) {
      return value.id;
    });

    async.map(position_ids, load_candidate, function(err, result2) {
      // Abort on error
      // This will be called if ANY of the individual load_candidate() request fails
      if(err) {
        console.log(err);
        return;
      }
      // result2 is now an array of results of each AJAX request

      result1.forEach(function(value1, index1) {

        // Create your outer div
        var textToInsert = '';
        textToInsert += '<div class="card bg-primary text-center"><div class="card-body"><h4 class="text-white m-0" id="position">' + value1['position'] + '</h4></div></div><br><div class="row">';
        // append each result of 2nd request to that div 
        result2[index1].forEach(function(value2, key) {
          textToInsert += '<div class="col-lg-4 col-sm-6 text-center mb-4"><h3>' + value2['name'] + '</h3><p>' + value2['candidate_number'] + '</p></div>';
        });

        // then close it and append it to your list
        textToInsert += '</div>';
        $('#candidate_list').append(textToInsert);

      });

    });
  },
  ajax_error_handler);
}

// Your id variable has to be defined somewhere
load_candidates(id);

-1
投票

在第二个ajax请求中使用async属性并将其设置为false。默认情况下,AJAX请求是异步的。他们不会等到响应来自服务器。

用以下内容替换第二个ajax:

$.ajax({
url: 'admin/requests/Get-Candidate_Per_Position.php',
method: 'POST',
data: {
    position_id: position_id
},
dataType: 'json',
async: false,
success: function(data) {
    $.each(data, function(key, value) {
        textToInsert += '<div class="col-lg-4 col-sm-6 text-center mb-4"><h3>' + value['name'] + '</h3><p>' + value['candidate_number'] + '</p></div>';
    });
}});

供你参考:

  1. http://api.jquery.com/jQuery.ajax/
  2. https://stackoverflow.com/a/1478322/3910232
© www.soinside.com 2019 - 2024. All rights reserved.