Ajax回调模式搜索的问题

时间:2017-11-03 06:03:44

标签: php jquery html mysql ajax

大家好我有问题我从abc.php调用ajax搜索脚本并且MySQL查询工作正常但是当我通过ajax搜索时它会提供一切结果

这是MySQL查询:

$query = "select * from tableName where column1 like '%pattern%' or column2 like '%pattern' or column_n like '%pattern'"; 

这是我的Ajax代码

function showHint(str) {    
  if (str.length==0) { 
    document.getElementById("txtHint").innerHTML="";

    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("txtHint").innerHTML=this.responseText;     
    }
  }  
  xmlhttp.open("GET","abc.php?q="+encodeURIComponent(str),true);

  xmlhttp.send();
}

这是我的abc.php

<?php
include "databaseconnect.php";
$id = trim($_GET['q']);

        $res = $con->prepare('select count(*) from tablename where column = 1 AND (column = ? OR column like ? OR column like ? OR column like ? OR column like ? OR column like ? OR column like ? OR column like ?)');
        $res->execute(array("$id","%$id%","%$id%","%$id%","%$id%","%$id%","%$id%","%$id%"));

        if($res->fetchColumn() > 0) {

    $query = $con->prepare('select * from tablename where column = 1 AND (column = ? OR column like ? OR column like ? OR column like ? OR column like ? OR column like ? OR column like ? OR column like ?)');
        $query->execute(array("$id","%$id%","%$id%","%$id%","%$id%","%$id%","%$id%","%$id%"));
?>
<?php
while($row = $query->fetch(PDO::FETCH_ASSOC)){

    print_r($row);
}
        }

?>

这是我的HTML代码

<form onsubmit="return false;"> 
<input type="text" autocomplete="off" autofocus="autofocus" onkeyup="showHint(this.value)" class="form-control input-lg gap-top" placeholder="Search for...">
</form>
<div class="container-fluid">
<div class="table-responsive">
<p><span id="txtHint"></span></p>

1 个答案:

答案 0 :(得分:0)

好的,我要写下一些不同的代码:

在MYSQL中:

CREATE TABLE `test`.`words` (
`wordid` INT NOT NULL AUTO_INCREMENT,
`word_one` VARCHAR(45) NULL,
 `word_tow` VARCHAR(45) NULL,
 PRIMARY KEY (`wordid`));

INSERT INTO `test`.`words` (`word_one`, `word_tow`) VALUES ('a', 'd');
INSERT INTO `test`.`words` (`word_one`, `word_tow`) VALUES ('ab', 'de');
INSERT INTO `test`.`words` (`word_one`, `word_tow`) VALUES ('abc', 'def');

在HTML中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>StackOverFlow</title>

    <script
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous">
    </script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
<form onsubmit="return false;">
    <input type="text" autocomplete="off" autofocus="autofocus"  class="form-control input-lg gap-top" placeholder="Search for...">
</form>
<div class="container-fluid">
    <div class="table-responsive">
        <p><span id="txtHint"></span></p>

</body>
</html>

在JavaScript(app.js)中:

$(document).ready( function(){

    $('.form-control.input-lg.gap-top').keyup(function() {

        let fd = new FormData();
        let word = $(this).val();

        fd.append('my_word', word);


        $.ajax({
            url: "abc.php",
            type: "POST",
            data: fd,
            processData: false,
            contentType: false,

            complete: function (results) {
                try {
                    let str = JSON.parse(results.responseText);
                    console.log(str)
                } catch (e) {
                    console.error(e);
                }
            },
        });


    }) ;


});

在PHP(abc.php)中:

<?php

$host = '127.0.0.1';
$dbname = 'test';
$username = 'kmoshe';
$password = 'password';
$charset = 'utf8';
$collate = 'utf8_unicode_ci';

$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=$charset", $username, $password,
    array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_PERSISTENT => false,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset COLLATE $collate"
    )
);


$word_to_find = $_REQUEST['my_word'];

$stmt = $pdo->prepare("SELECT * FROM words WHERE word_one like :w");
$stmt->execute(['w' => "%$word_to_find%"]);


$array_of_words = [];

while($row = $stmt->fetch()) {
    $array_of_words[] = $row['word_one'];
}

echo json_encode($array_of_words);