我想为私人消息实现小型用户自动搜索功能。我找不到以下代码无法正常工作的原因。 JS Ajax每次都会在.fail节点中结束,尽管事实是DB中有一个用户,例如以“ m”开头。
js:
$($userSearchForm).on('keyup', function () {
var $query = $('#userSearch').val();
$
.ajax({
url: '../../../rest/restEndPoints/Privatemessage.php',
type: 'POST',
data: $query
})
.done(function (response) {
console.log(response);
})
.fail(function (error) {
console.log('Username not found', error);
});
});
Privatemessage.php REST端点:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["userSearchForm"])) {
$query = $_POST["userSearch"];
$queryResult = Privatemessage::searchByUsername($conn, $query);
$response = ['success' => $queryResult];
}
私人消息类
static public function searchByUsername(PDO $pdo, $userName) {
$stmt = $pdo->prepare("SELECT u.username FROM Users u WHERE userName LIKE CONCAT('%',:userName,'%')");
$result = $stmt->execute([
'userName' => $userName
]);
$ret = [];
if ($result === true && $stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$loadedUsername = new Privatemessage($pdo);
$loadedUsername->userName = $row['username'];
$ret[] = $loadedUsername;
}
return $ret;
}
return null;
}
privateMessage.php子页面上的HTML:
<form class="form-user-search" id="userSearchForm" action="" method="post">
<div class="form-group">
<label for="userSearch">Find user</label>
<input name="userSearch" id="userSearch" class="form-control" placeholder="Find user" autofocus>
<input name="newPrvMessage" id="newPrvMessage" class="form-control" placeholder="Type in message" autofocus>
<div id="userSearch" style="display:none;"></div>
<button class="btn btn-default btn-block" type="submit" id="userSearchButton">Submit new private message</button>
</div>
</form>
尽管“未找到”类,但子页面仍然可以正确提取已发送/接收的消息( rest.php 文件动态包含.php类/端点,具体取决于您通过导航栏输入的子页面)