javascript - HTML 表格不显示列中的内容

标签 javascript html ajax

用户可以搜索数据库中包含的人员,在输入文本中引入搜索词。 我使用以下 Ajax 脚本来显示从 JSON 接收的数据库对象:

<script type="text/javascript">
 $(document).ready(function() {
     
    // With JQuery
$("#ex6").slider();
$("#ex6").on("slide", function(slideEvt) {
    $("#ex6SliderVal").text(slideEvt.value);
});

 $('#keyword').on('input  keyup change', function() {
 var searchKeyword = $(this).val();
 if (searchKeyword.length < 3) {
      $('ul#content').empty()
 }
 if (searchKeyword.length >= 1) {
    
 $.post('search.php', { keywords: searchKeyword }, function(data) {
 $('#content').empty()
 $('#content').append('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead><tbody>')
    
if (data == ""){
     $('#content').append('No hay resultados para su búsqueda') 
}
 
 $.each(data, function() {
    
      
 $('#content').append('<tr><td>'+this.nombre_doctor +'</td><td>'+ this.apellido1_doctor + '</td><td>'+ this.apellido2_doctor+'</td></tr>');

      
 });
  $('#content').append('</tbody></table>')  
 }, "json");
 }
 });
 });
 </script>

这是用户输入搜索词时的输出:

enter image description here

正如您在图片中看到的,对象没有显示在预期的列上。

脚本中有什么问题?

最佳答案

当您调用append时jQuery 使用字符串构造一个对象并附加该对象。换句话说,append('<foo>')真是append($('<foo'>) 。此代码中“append 附加原始 HTML”的假设是不正确的。

你想要类似的东西

var $table = $('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead></table>').appendTo('#content');
var $tbody = $('<tbody></tbody>').appendTo($table);

$.each(data, function() {
    var $tr = $('<tr>').appendTo($tbody);
    $('<td>').text(this.nombre_doctor).appendTo($tr);
    $('<td>').text(this.apellido1_doctor).appendTo($tr);
    $('<td>').text(this.apellido2_doctor).appendTo($tr);
});
// Nothing with </tbody></table> , those elements already exist

请注意,您当前的代码包含一个重大漏洞,因为它允许控制您数据的每个人inject arbitrary HTML and JavaScript into your website 。使用 text 避免了这种情况。

关于javascript - HTML 表格不显示列中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36971990/

相关文章:

javascript - document.write 和委托(delegate)事件处理程序持久化

javascript - reactjs,jsx 遍历嵌套对象

javascript - Dojo:获取对 dijit.form.Select 中单击项的访问权限?

html - 新内容迫使网站顶部 - 有一些基本的布局问题 -

jquery - Twitter Bootstrap 下拉菜单在点击时禁用了按钮的原始功能

php - 在 AJAX 中显示数据库数据的错误位置

javascript - 当文本区域/输入模糊/失去焦点时仍然显示 div

html - 更改表格行高 - Bootstrap

html - 如何在 CSS3 中绘制自定义圆形?

ajax - Liferay 6.2 ajax portlet 内容渲染