AJAX实时搜索未返回结果

时间:2016-05-04 10:46:20

标签: php jquery ajax search

我一直在努力设置这个AJAX实时搜索一段时间,但无法让它工作。

它连接到服务器(我希望),因为我没有收到任何错误告诉我这个,但现在我什么也没得到。

这是我正在使用的php。我认为问题出在这里,但我无法看到它。我猜它有我在桌子上命名字段的方法吗?

<?php
/************************************************
    The Search PHP File
************************************************/


/************************************************
    MySQL Connect
************************************************/

// Credentials
$dbhost = "localhost";
$dbname = "zackreid_test2";
$dbuser = "zackreid_test";
$dbpass = "test2";

//  Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");

//  Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %s\n", $tutorial_db->connect_error);
    exit();
}

/************************************************
    Search Functionality
************************************************/

// Define Output HTML Formating
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';

// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // Build Query
    $query = 'SELECT * FROM search WHERE function LIKE "%'.$search_string.'%" OR name LIKE "%'.$search_string.'%"';

    // Do Search
    $result = $tutorial_db->query($query);
    while($results = $result->fetch_array()) {
        $result_array[] = $results;
    }

    // Check If We Have Results
    if (isset($result_array)) {
        foreach ($result_array as $result) {

            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['function']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['name']);
            $display_url = 'http://php.net/manual-lookup.php?pattern='.urlencode($result['function']).'&lang=en';

            // Insert Name
            $output = str_replace('nameString', $display_name, $html);

            // Insert Function
            $output = str_replace('functionString', $display_function, $output);

            // Insert URL
            $output = str_replace('urlString', $display_url, $output);

            // Output
            echo($output);
        }
    }else{

        // Format No Results Output
        $output = str_replace('urlString', 'javascript:void(0);', $html);
        $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
        $output = str_replace('functionString', 'Sorry :(', $output);

        // Output
        echo($output);
    }
}


?>

以下是需要的html;

<!DOCTYPE HTML>
<html>
<head>
    <!-- Meta -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Live Search Tutorial</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <!-- Load CSS -->
    <link href="style/style.css" rel="stylesheet" type="text/css" />
    <!-- Load Fonts -->
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:regular,bold" type="text/css" />
    <!-- Load jQuery library -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <!-- Load custom js -->
    <script type="text/javascript" src="scripts/custom.js"></script>
</head>
<body>
    <div id="main">

        <!-- Main Title -->
                <h1 class="title">Periodic Tabel Search</h1>
        <h5 class="title">A simple why to find the element you are looking for</h5>

        <!-- Main Input -->
        <input type="text" id="search" autocomplete="off">

        <!-- Show Results -->
        <h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
        <ul id="results"></ul>


    </div>

</body>
</html>

此处还有一个我目前正在测试的测试版本

http://dev.zackreid.com/test/download/Code/index.html

哦,列的名称是id,function和name。通过浏览php文件,我认为这些文件被引用了?

修改

只需添加JavaScript;

/* JS File */

// Start Ready
$(document).ready(function() {  

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    // Live Search
    // On Search Submit and Get Results
    function search() {
        var query_value = $('input#search').val();
        $('b#search-string').text(query_value);
        if(query_value !== ''){
            $.ajax({
                type: "POST",
                url: "search.php",
                data: { query: query_value },
                cache: false,
                success: function(html){
                    $("ul#results").html(html);
                }
            });
        }return false;    
    }

    $("input#search").live("keyup", function(e) {
        // Set Timeout
        clearTimeout($.data(this, 'timer'));

        // Set Search String
        var search_string = $(this).val();

        // Do Search
        if (search_string == '') {
            $("ul#results").fadeOut();
            $('h4#results-text').fadeOut();
        }else{
            $("ul#results").fadeIn();
            $('h4#results-text').fadeIn();
            $(this).data('timer', setTimeout(search, 100));
        };
    });

});

EDIT2

我意识到当我在搜索栏中输入值时会发生错误。我一直这样做;

POST http://dev.zackreid.com/test/download/Code/search.php 500 (Internal Server Error)

send @ jquery.min.js:4
f.extend.ajax @ jquery.min.js:4
search @ custom.js:17

jquery.min.js:4

所以这意味着php文件有问题吗?哪个与jquery连接失败?

2 个答案:

答案 0 :(得分:2)

我用while包裹你的if循环然后它对我有用。

if ($result) {
    while($results = $result->fetch_array()) {
        $result_array[] = $results;
    }
}

即使fetch_array()是布尔值,$result也始终在运行。

答案 1 :(得分:1)

<?php
/************************************************
    The Search PHP File
************************************************/


/************************************************
    MySQL Connect
************************************************/

// Credentials
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "123456";

//  Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");

//  Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %s\n", $tutorial_db->connect_error);
    exit();
}

/************************************************
    Search Functionality
************************************************/

// Define Output HTML Formating
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';

// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_REQUEST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // Build Query
    $query = 'SELECT * FROM search WHERE function LIKE "%'.$search_string.'%" OR name LIKE "%'.$search_string.'%"';

    // Do Search
    $result = $tutorial_db->query($query);

    // while($results = $result->fetch_array()) {
    if ($result) {
        while($results = $result->fetch_array()) {
            $result_array[] = $results;
        }
    }

    // Check If We Have Results
    if (isset($result_array)) {
        foreach ($result_array as $result) {

            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['function']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['name']);
            $display_url = 'http://php.net/manual-lookup.php?pattern='.urlencode($result['function']).'&lang=en';

            // Insert Name
            $output = str_replace('nameString', $display_name, $html);

            // Insert Function
            $output = str_replace('functionString', $display_function, $output);

            // Insert URL
            $output = str_replace('urlString', $display_url, $output);

            // Output
            echo($output);
        }
    }else{

        // Format No Results Output
        $output = str_replace('urlString', 'javascript:void(0);', $html);
        $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
        $output = str_replace('functionString', 'Sorry :(', $output);

        // Output
        echo($output);
    }
}


?>

名为http://localhost/test/so_q.php?query=h

的网址

的MySQL

mysql> desc search;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| function | varchar(200) | YES  |     | NULL    |       |
| name     | varchar(50)  | YES  |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

数据

mysql> select * from search;
+----------+------+
| function | name |
+----------+------+
| h        | john |
| asdf     | john |
| hey      | Dakz |
| ado      | Sira |
+----------+------+
4 rows in set (0.00 sec)