2个结果匹配

时间:2015-09-05 19:00:22

标签: javascript php jquery html ajax

你有一个用php,jquery和ajax进行ajax搜索,在db中搜索articles表中的名称和描述。当字符串仅与一个结果匹配时,它可以正常工作,但如果有2个匹配的结果,则显示内部服务器错误。你可以在这里看到(http://en.organizing-erasmus.es/events/),尝试在搜索中写“tr”并尝试写“ju”(这个字符串有两个匹配的结果,所以它在chrome控制台中显示500服务器错误。

Search.php代码:

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

require('classes/Article.php');

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

// Credentials
$dbhost = "localhost";
$dbname = "hidden";
$dbuser = "hidden";
$dbpass = "hidden";

//  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 href="urlString">';
$html .= '<h4>nameString</h4>';
$html .= '<p>functionString</p>';
$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 articles WHERE title_eng LIKE "%'.$search_string.'%" OR summary_eng LIKE "%'.$search_string.'%" OR content_eng 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) {
            function limpiarCaracteresEspeciales($string ){
     $string = htmlentities($string); 
     $string = str_replace(' ', '-', $string);
     $string = preg_replace('/\&(.)[^;]*;/', '\\1', $string); 
     return $string; 
}
$id_s = htmlspecialchars( $result['id'] );
    $titulo = htmlspecialchars( $result['title_eng'] );
           $title_url = limpiarCaracteresEspeciales($titulo);


            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['summary_eng']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['title_eng']);
            $eve = 'events';
            $display_url = '/'.$eve.'/'.$title_url.'/'.$id_s.'/';

            // 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 he encontrado nada.</b>', $output);
        $output = str_replace('functionString', 'Lo siento, no me pegues plis :(', $output);

        // Output
        echo($output);
    }
}


/*
// Build Function List (Insert All Functions Into DB - From PHP)

// Compile Functions Array
$functions = get_defined_functions();
$functions = $functions['internal'];

// Loop, Format and Insert
foreach ($functions as $function) {
    $function_name = str_replace("_", " ", $function);
    $function_name = ucwords($function_name);

    $query = '';
    $query = 'INSERT INTO search SET id = "", function = "'.$function.'", name = "'.$function_name.'"';

    $tutorial_db->query($query);
}
*/
?>

custom.js(JQuery代码)

/* JS File */

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

    // Icon Click Focus
    $('.buscar-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").on("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();
            $('p#results-text').fadeOut();
        }else{
            $("ul#results").fadeIn();
            $('p#results-text').fadeIn();
            $(this).data('timer', setTimeout(search, 100));
        };
    });


});


$("input#search").on("keydown", function(e) {
        var $listItems = $('ul#results li');
        var $listItemsa = $('ul#results li a');

             var key = e.keyCode,
        $selected = $listItems.filter('.selected'),
        $current;

    if ( key != 40 && key != 38 ) return;

    $listItems.removeClass('selected');

    if ( key == 40 ) // Down key
    {
        if ( ! $selected.length || $selected.is(':last-child') ) {
            $current = $listItems.eq(0);
        }
        else {
            $current = $selected.next();
        }
    }
    else if ( key == 38 ) // Up key
    {
        if ( ! $selected.length || $selected.is(':first-child') ) {
            $current = $listItems.last();
        }
        else {
            $current = $selected.prev();
        }
    }
    $.fn.focusWithoutScrolling = function(){
var x = $(document).scrollLeft(), y = $(document).scrollTop();
  this.focus();
  window.scrollTo(x, y);
  return this; //chainability

};
var $currenta = $current.children();
$currenta.focusWithoutScrolling();
    $current.addClass('selected');
    event.preventDefault();
        });

标记:

    <div id="main">
<!-- Main Input -->
<input type="text" id="search" autocomplete="off">
<i class="fa fa-search fa-2x buscar-icon"></i>

<!-- Show Results -->
<ul id="results"></ul>

      

0 个答案:

没有答案