阻止Ajax追加到DIV

Stop Ajax from Appending to DIV

本文关键字:DIV 追加 Ajax 阻止      更新时间:2023-09-26

我有这个AJAX代码:

$.ajax({
    target: "#map",
    dataType: "json",
    type: 'GET',
    data: {
        query: query
    },
    url: 'http://localhost:8080/path/urllinks',
    success: function(response) {
        successCallback(response);
    }
});
function successCallback(responseObj) {
      #I tried adding the suggested answers here but it's not working.
  var table_0 = document.createElement('table');   
  if ( responseObj.length == 0 ) {
      var p_0 = document.createElement('p');
       p_0.appendChild( document.createTextNode(" Search is keyword :"+query + " does not exist in our record") );
    document.body.appendChild( p_0 );
    }
  $.each(responseObj, function(index, element){

         var tr_0 = document.createElement('tr');
            var td_0 = document.createElement('td');
               td_0.style.fontSize = "18px";
               td_0.style.textDecoration = "underline";
               td_0.style.color = "blue";
               var a_0 = document.createElement('a');
                  a_0.href = element.link;
                  a_0.appendChild( document.createTextNode(element.title) );
               td_0.appendChild( a_0 );
            tr_0.appendChild( td_0 );
         table_0.appendChild( tr_0 );

         var tr_1 = document.createElement('tr');
            var td_1 = document.createElement('td');
               td_1.style.color = "green";
               td_1.style.fontSize = "14px";
               var p_0 = document.createElement('p');
                  p_0.appendChild( document.createTextNode(element.link) );
               td_1.appendChild( p_0 );
            tr_1.appendChild( td_1 );
         table_0.appendChild( tr_1 );

         var tr_2 = document.createElement('tr');
            tr_2.style.height = "30px";
         table_0.appendChild( tr_2 );
      document.body.appendChild( table_0 );
  });       
   }

在我的JSP页面中,我将目标div元素设置为:

<div id="map"></div>

每次我按下表单提交,AJAX都会追加结果,并且列表继续增长。我想在#map中创建一个新的结果表。

您的代码中有这样一行:

document.body.appendChild( table_0 );

那,告诉您的document对象(您的页面)找到body标记,然后附加table_0的内容(因此,您没有将表附加到#map元素,但是,总是在页面的末尾…

document.body.appendChild( table_0 );替换为$("#map").html(table_0);

,然后,$("#map").empty();将在这个函数调用的开始工作。


顺便说一句。有很多更简单的方法来从头创建一个表……当你得到JSON格式的数据时,看看DataTables插件,更多的是Ajax源数据…

您是否尝试在成功回调函数中删除div内容?

。,你可以使用jquery $('#map').empty()删除所有的子元素,然后添加新的数据。

或者,您也可以在成功回调函数中执行$('#map').html(response)。

希望能有所帮助。