问题
I'm trying to make autocomplete with php array and jquery autocomplete function. My code creates array in separate php script and it stores the array in session global variable. Then in the main script I have a form and a jquery function that uses autocomplete but it doesn't work I tried it with a static array and it worked but when I try it with a dynamic array it doesn't work and I would like your help on how to do it so it will work.
index.php
<?php
session_start();
$tags = $_SESSION['autocomplete'];
?>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<form id="autocom" action="" method="post" autocomplete="off">
<fieldset>
<legend>Search</legend>
<input id="auto" type="text" name="search">
<input type="submit" name="submit">
</fieldset>
</form>
<script type="text/javascript">
$(function() {
var availableTags = <?php echo json_encode($tags); ?>;
console.log(availableTags);
$( "#autocom" ).autocomplete({
source: availableTags
});
});
</script>
search.inc.php
<?php
session_start();
$dir = '../.';
$a = scandir($dir);
$searchQuery = $_GET['q'];
$arr = array("<", ">", "!DOCTYPE", "html", "head", "body", "div", "table", "tr", "th", "td", "php", "?");
$foundQueries = array();
foreach ($a as $value) {
if (strpos($value, ".php")) {
$find = "../".$value;
if (stripos(file_get_contents($find), $searchQuery) && !in_array($searchQuery, $arr)) {
$tagname = 'p';
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match_all($pattern, file_get_contents($find), $matches);
print_r($matches);
echo $value;
foreach ($matches as $pending) {
foreach ($pending as $found) {
if (stripos($found, $searchQuery)) {
$endFound = str_replace("<p>", "", $found);
$foundQueries[$value][] = str_replace("</p>", "", $endFound);
}
}
}
echo '<xmp>';
print_r($foundQueries);
echo '</xmp>';
$_SESSION['autocomplete'] = $foundQueries;
}
}
}
?>
回答1:
In jQuery you should be targeting the input element not the form.
Change $( "#autocom" ).autocomplete({
to $( "#auto" ).autocomplete({
.
来源:https://stackoverflow.com/questions/52089733/php-autocomplete-with-jquery