Javascript到PHP的输入是空的.实时搜索PHP麻烦



当我在输入中输入某些内容时,它是空的。

这是HTML表单和JS。

$(function() {
$("#search").keyup(function() {
var search = $("#search").val();
$.ajax({
type: "POST",
url: "search.php",
data: {
"search": search
},
cache: false,
success: function(response) {
$("#resSearch").html(response);
}
});
return false;
});
});
<div id="search">
<form action="search.php" method="post">
<input type="text" name="search" placeholder="search" id="search">
<input type="submit" name="dosearch" style="display: none;">
</form>
</div>
<div id="resSearch"></div>

还有搜索.php

<?php
require_once 'functions/functions.php';
global $mysqli;
connectDB();
$search = $_POST['search'];
$search = addslashes($search);
$search = htmlspecialchars($search);
$search = stripslashes($search);
$results = R::findAll('games', 'name LIKE :name', array(':name' => '%' . $search . '%') );
closeDB();
$export = R::exportAll($results);
if(!empty($export)){
$final = $export;
var_dump($search);
var_dump($final);
$result = $final[0]['name'];
echo $result;
} else {
echo 'No results';
}
?>

当我在输入中输入某些内容并使用 var_dump($search( 检查它时,它说该变量为空,但是当我按回车键(提交(时,它会重定向我的搜索.php并且变量$search不为空,它采用我在输入中输入的值;

文档中不能有多个 id。您需要更改元素的 id 以使它们唯一。我已经更新了您的代码段和控制台日志搜索值。

$(function() {
$("#search").keyup(function() {
var search = $(this).val();
console.log(search)
$.ajax({
type: "POST",
url: "search.php",
data: {
"search": search
},
cache: false,
success: function(response) {
$("#resSearch").html(response);
}
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search-wrapper">
<form action="search.php" method="post">
<input type="text" name="search" placeholder="search" id="search">
<input type="submit" name="dosearch" style="display: none;">
</form>
</div>
<div id="resSearch"></div>

@YourLogarithm,我看到你有 2 个 id = search 的元素,一个是div,另一个是输入。您不能有重复的 ID。

最新更新