文本未标记

Text not marking up

我正在编写一个页面,允许锦标赛主管 (TD) 将玩家添加到活动中。当 TD 去搜索播放器时,我希望搜索结果显示在搜索输入下方的 keyup 上(无需刷新页面)。 在这个阶段,我有 2 个 php 页面和 1 个 js 页面,并且进行了实时搜索,但输出没有得到标记。我已经编写了一段代码将 PHP $_SESSION[''] 数组转换为 javascript 数组,但我的大脑正在煎炸,我不知道从这里去哪里。

我实际上希望将此代码的处理版本作为输出(假设 SQL returns 只有 1 个名为 John Smith 的玩家)

<tr></td> 123 </td><td> John Smith </td></tr>

我的 php 主页有:

<table border='1px'>
<tr><th colspan='6'> <?php echo ($eName . " - " . $vn); ?></th></tr>
<tr><th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th></tr>

<tr><td colspan='3'>Search <input type='text' id='newsearch'</input>
</table>
<br>

<div id="newsearch-data"> </div>

<script>
 var players = [];   
</script>    

<?php

//Makes php array into js array
foreach ($_SESSION['players'] as $id){
echo "<script> players.push('" . $id . "') </script>";
}

?>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script>
<script src="global.js"> </script>

js 页面:

$('input#newsearch').on('keyup', function(){
    var newsearch = $('input#newsearch').val();
    if ($.trim(newsearch)!= "") {
        $.post('newsearch.php', {newsearch: newsearch}, function(data) {
            $('div#newsearch-data').text(data);
        });
    }
});

第 2 php 页

<?php
  session_start();
  unset($_SESSION['players']);
if (isset($_POST['newsearch']) === true && empty($_POST['newsearch'] === false)){
require 'dbconnect.php';

$term = $_POST['newsearch'];
$terms = "%" . $term . "%";

$_SESSION['players'] = array();

$query = ("SELECT * FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);

        while ($dbsearch = mysqli_fetch_assoc($run_query))
         {
         array_push ($_SESSION['players'],$dbsearch['PlayerID']);
           echo "<tr><td>" . $dbsearch['PlayerID'] . "</tr></td>";

         }}?

如何在 html table 而不是原始 html 代码上输出新行?

您需要 .html() 将输出呈现为 HTML 而不是 .text(),因为 .text() 会将结果输出为原始数据,然后试试这个解决方案:

$('div#newsearch-data').html(data);

Live example - 记入@Peter Bailey 的实例。

参考资料

  1. http://api.jquery.com/html/ - .html()
  2. http://api.jquery.com/text/ - .text()

替换$('div#newsearch-data').text(data);

$('div#newsearch-data').html(data);

$.text() 对输入字符串进行转义,当您知道输入是一个字符串并且您想要预设它时应该使用它 "as is"。如果输入包含您要注入 DOM 的实际 HTML,则 $.html() 是您的朋友:-)