正确显示ajax请求到html的结果

时间:2016-04-23 04:48:36

标签: javascript jquery ajax

我刚刚使用JQuery的AJAX函数做了一个简单的请求,该函数将在完成请求时检索数据。这是我的代码:

.triangle-up {
    display: inline-block;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 8px solid green;
    bottom: 1em;
}

.triangle-down {
    display: inline-block;
    bottom: 1em;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 8px solid red;
}  

它工作得非常好,它确实收到了数据。但问题是,每次单击提交按钮发出新请求时,检索到的结果都会附加到之前结果的末尾。

我知道这是因为('.submit').on('click', function(e){ e.preventDefault(); var tobesent = $('input.test').val(); $.ajax({ type : 'POST', dataType : 'json', url : '<?php echo base_url("ajaxcontroller/submit"); ?>', data : {'content' : tobesent} }) .done(function(data){ $.each(data, function(k, v){ $('div.placedhere').append(v.fullname); }) }) .fail(function(data){ console.log(data); }) });

如何在开始发出新请求之前清除div,以便div只显示最新结果?

我在$('div.placedhere').append(v.fullname)之前完成了$('div.placedhere').remove()这样的事情,但div只显示了检索到的数据中的最后一条记录。

我还尝试将$('div.placedhere').append(v.fullname)函数更改为append()函数,我得到了相同的结果,div只显示了数据的最后一条记录。

如何在开始发出新请求之前清除div,以便div只显示最新结果?

2 个答案:

答案 0 :(得分:1)

  

如何在开始发出新请求之前清除div,以便div   只显示最新结果?

您可以使用.empty()

 var div = $("div.placedhere"); // cache selector outside of `click` handler
 .done(function(data) {
   div.empty(); // remove child nodes of `div.placedhere`
   $.each(data, function(k, v){
    div.append(v.fullname);
   })
 })

答案 1 :(得分:0)

你可以通过双向

完成

1)在ajax调用之前清除div

('.submit').on('click', function(e){

   e.preventDefault();

   $('div.placedhere').empty(); //clear div before ajax call

   var tobesent  = $('input.test').val();
   $.ajax({
     type : 'POST',
     dataType : 'json',
     url : '<?php echo base_url("ajaxcontroller/submit"); ?>',
     data : {'content' : tobesent}
  })
  .done(function(data){
     $.each(data, function(k, v){
     $('div.placedhere').append(v.fullname);
  })
}).fail(function(data){
     console.log(data);
  })
});

2)使用HTML代替APPEND html使div为空,然后附加新值)

('.submit').on('click', function(e){

   e.preventDefault();

   var tobesent  = $('input.test').val();
   $.ajax({
     type : 'POST',
     dataType : 'json',
     url : '<?php echo base_url("ajaxcontroller/submit"); ?>',
     data : {'content' : tobesent}
  })
  .done(function(data){
     $.each(data, function(k, v){
     $('div.placedhere').html(v.fullname); // use `html` like this
  })
}).fail(function(data){
     console.log(data);
  })
});