2016-04-23 49 views
0

我只是使用JQuery的AJAX函數提出了一個簡單的請求,它將在請求完成後檢索數據。這是我的代碼:正確顯示從ajax請求到html的結果

('.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.placedhere').append(v.fullname)

如何在我開始提出新請求之前清除div,以便div只顯示最新結果?

我在$('div.placedhere').append(v.fullname)之前做了$('div.placedhere').remove()之類的事情,但div只顯示檢索到的數據中的最後一條記錄。

我也曾嘗試將append()函數改爲html()函數,我得到了相同的結果,div只顯示了我最後一次記錄的數據。

如何在我開始提出新請求之前清除div,以便div只顯示最新結果?

回答

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); 
    }) 
}) 
0

您可以通過2路才

1)明確的div Ajax調用做到這一點

('.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代替APPENDhtml使得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); 
    }) 
});