用户可以搜索数据库中包含的人员,在输入文本中引入搜索词。 我使用以下 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>
这是用户输入搜索词时的输出:
正如您在图片中看到的,对象没有显示在预期的列上。
脚本中有什么问题?
最佳答案
当您调用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/