繁体   English   中英

以特定顺序更新带有ajax响应数据的列表

[英]Updating a list with ajax response data in a specific order

我有一个ajax请求,它根据数组中请求对象的数量被调用多次。 这些对象在数组内部的顺序很重要,并且需要以相同的顺序反映在动态生成的列表中。 当服务器发回每个响应时,我将更新<ul> ,如下所示。

     $.ajax({
        type: 'POST',
        url: baseServiceURL + 'report/',
        processData: false,
        dataType: 'json',
        contentType: 'application/json',
        data: payload,
        crossDomain: true,
    })
    .done(function (response) {
        updateUI(response);
    })
    .fail(function (jqXHR, textStatus) {
       // handle failure 
    });


var updateUI = function (response) {
    // Update the drop-down list
    $('#dropdown').append('<li><a class="dd-option" data-value="' + response.ReportName + '" data-path="' + response.ReturnURL + '" href="#">' + response.ReportName + '</a></li>');

    // do more stuf...
};

如何以正确的顺序显示响应的方式动态构建列表? 我做的一件事是向请求添加一个order参数,该参数的值是该请求对象在数组中的索引。 我的想法是我的服务可以将该值发送回响应中,因此javascript可以对其进行操作。

编辑: 这里问题是询问基本相同的问题,除了使用getJSON命令并附加div,而我使用的是帖子并附加<li>元素。

这里有两种可能的策略。

  1. 收到响应后立即更新您的UI,如果收到新值,则重新渲染
  2. 等待所有ajax答复完成,然后呈现您的UI

对于(1),您应该只保留所有项目的总计

var $dropdown = $('#dropdown');
var renderDropdown = function(reports) {
   //use lodash or underscore.js here cause implementing this manually is annoying
   var sortedSelections = _.sortBy(reports, 'order');
   var htmlPerItem = sortedSelections.map(function(item) {
      return '<li><a ..... </li>';
   });
   $dropdown.html(htmlPerItem.join(''));
}

var reportSelections = [];
payloads.map(function(payload) {
  $.ajax({ ... })
   .then(function(response) {
      reportSelections.push(response);
      renderDropdown(reportSelections);
   })
})

对于(2),您可以使用jquery $.when

var gettingResults = payloads.map(function(payload) {
    return $.ajax({ .... });
});
$.when(gettingResults).then(function() {
  //the first arg will be response1, the second response2, etc
  var reportSelections = _.sortBy(arguments, 'order');
  renderDropdown(reportSelections);
});

请注意,在(1)中,每个项目仅渲染一次,但随着项目的进入而获得更新视图。在(2)中,您仅渲染一次,但必须等待所有加载完成。

当然,(1)的变体是您不重新渲染任何东西,而只是在加载项目时将它们插入正确的位置。 这将更加难以调试和编写更多代码,因此我将其作为读者的练习(使用jquery的$.fn.data将原始项目与元素一起存储)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM