【问题标题】:Reload div with same content重新加载具有相同内容的 div
【发布时间】:2013-11-26 18:15:58
【问题描述】:

我有一个 div,其中包含从 Mysql 中提取的客户端列表。

在同一页面上,我有一个弹出的 jquery 对话框,允许用户添加新客户端。

我想要发生的是,当用户添加新客户端时,包含列表的列表会重新加载,以便新客户端可用。

有没有办法在不使用 Load() 函数的情况下简单地重新加载 div,因为这会在我重新声明填充列表的类时导致错误?

【问题讨论】:

  • 是的,使用 .load 使用的底层 $.ajax 方法。但是,.load 可能会更容易。
  • 请提供您已经尝试过的示例。
  • 是否必须将新客户端添加到数据库中?如果没有,您可以使用 jquery 创建元素并将其附加到 DOM
  • 您是否从 ajax 请求中检索用户信息?

标签: javascript jquery html mysql css


【解决方案1】:

当然。如果不查看您的代码,您在这里的困惑表明您不了解“关注点分离”。将获取信息的过程与显示该信息的过程分开。当用户输入新信息时,将其添加到您从服务器获得的信息的 javascript 数组或对象中,并将其发送到服务器以在数据库中更新。然后使用更新的信息再次运行显示功能以包含新信息。理想情况下,如果可以,显示过程将使用现有标记,而不是全部删除并重新创建它只是为了添加一个项目。 Here's a very basic example (click here). 理想情况下,您会采用此概念并对其进行扩展,以使其具有最佳的效率和组织性。

这是来自我的 jsbin 的示例代码。请记住,这只是为了帮助您入门。

var info = [1,2,3,4,5]; //this is what you got from your ajax call to the server

function render(element, info) {
  //this is a lazy system that recreates/replaces all the markup each time. I suggest doing this more efficiently, but that is work for you to do :)
  var frag = document.createDocumentFragment();
  var len = info.length;
  for (var i=0; i<len; ++i) {
    var p = document.createElement('p');
    p.textContent = info[i];
    frag.appendChild(p);
  }
  element.innerHTML = '';
  element.appendChild(frag);
}

var targetElem = document.getElementById('targetElem');

render(targetElem, info);

var addButton = document.getElementById('add');
var input = document.getElementById('infoInput');
addButton.addEventListener('click', function() {
  info.push(input.value); //update the information
  render(targetElem, info); //render the updated information
});

【讨论】:

    【解决方案2】:

    其中任何一个都应该让您成功。

    success: function(userinfos) {
                     $("#users").append($('<tr><td>'+userinfos+'</td></tr>'))
                     display_message("user added");
                   }
    

     $.ajax({
    type: "GET",
    url: "ht.tp://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+ 
    occasionData     +"&relationship="+ forData +"#",
    
    success: function (response) {
    
        $("#testDIV").html(response);
    }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多