2016-01-24 93 views
0

我有一個搜索框,可以根據MySql數據庫中的數據給出建議結果列表。如果用戶鍵入A並且AppleAnimal字在數據庫中,則建議框將顯示兩個結果。目前,我無法單擊其中一個結果並填寫文本框,無論我嘗試做什麼,我似乎都無法使其工作。目前,我的東西,看起來像這樣的工作:點擊建議結果並填充文本框

echo '<script type ="text/javascript">'; 

    echo 'function textFill(){'; 
    echo ' var txt=document.getElementById("userInput").value= <li onclick ="textFill(this.value)">' .$matched[$count].'</li>'; //Suggestion results 
    echo '}'; 
    echo"</script>"; 
} 

我會說實話,我不知道這是否是即使是想在正確的道路,但我發現了幾個例子模糊地類似於這個,所以這就是我的方向。通過這種設置,建議框甚至不顯示,但是如果我拿走echo '<script type ='text/javascript>'它將顯示結果加上整行getElement代碼。我將如何去讓這個工作正常?如有必要,我可以展示更多代碼。

編輯: 我提供更多的代碼,以顯示更多我的PHP:

if(isset($_GET['userInput'])){ 
    $value = $_GET['userInput']; //assign the value 
    strtolower($value); 
    }else{ 
    echo "no input"; 
    } 
//Select query 

    $sql = "SELECT Device_type FROM Device WHERE Device_type LIKE '%".$value."%';"; 


    if($result = mysqli_query($conn, $sql)){ 
    if(mysqli_num_rows($result) > 0){ 
//Store the result in an array list[] 

    while($row = mysqli_fetch_array($result)){ 
    $list[] = $row['Device_type']; 
    } 
    }else{ 
//set a null value to list[] if no result to prevent error 

    $list[] = ""; 
    } 
    } 

    if(!empty($value)){ 
    if($matched = preg_grep('~'.$value.'~i', $list)){ 
    $count = 0; 
    echo '<ul>'; 
    while($count < sizeOf($list)){ 
    if(isset($matched[$count])){ 

     echo '<li > ' .$matched[$count].'</li>'; 

    } 
    $count++; 
    } 
    echo '</ul>'; 
    echo json_encode($data); 
    }else{ 
    echo "No result"; 
    } 
+0

您是否閱讀過在您的瀏覽器中按F12顯示的錯誤控制檯? –

+0

@NielsKeurentjes錯誤未捕獲ReferenceError:未定義jQuery。我有2頁,一個有我的輸入文本框,另一個處理數據庫連接和查詢。我在第一頁的''部分引用了',這是我的輸入框的內容,我還需要在數據庫連接/查詢頁面上使用它? – Jcmoney1010

+1

庫需要獨立包含在使用它們的每個*頁*中。如果您在iframe中加載此代碼,那是一個新頁面。如果你通過Ajax加載它(因爲我懷疑你沒有),它不是。但是,所有JS處理都會停止第一個致命錯誤,這是肯定的。 –

回答

0

假定你有以下文件送達您的Web服務器。

|- search.php 
|- index.html 

在您的index.html文件:

<!-- loading JQuery library --> 
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> 

<!-- code for capturing user input, sending it to server (search.php) and upon receiving suggestions populating them under the search box --> 
<script> 
$(document).ready(function() { 
    $('#searchbox').keyup(function() { // upon every key up when user is typing 
     $('#suggestions').html(''); // clear if any previous suggestions 

     var input = $(this).val(); 

     $.getJSON(// sending a GET request via AJAX expecting a JSON response 
      'search.php', // to this URL where the PHP file is 
      { 
       searchQuery: input // with the text user typed in 
      }, 
      function(data) { // upon receiving a response 
       $(data).each(function() { // iterate through the suggestions data received as JSON 
        var suggestion = '<option value=' + this + '>'; // create an <option> element with the each suggestion 
        $('#suggestions').append(suggestion); // and append it to the suggestions <datalist> 
       }); 
      } 
     }); 
    }); 
}); 
</script> 

<!-- search form --> 
<input id="searchbox" name="searchbox" type="search" list="suggestions"> 
<datalist id="suggestions"> 
    <!-- suggestions will be populated here when user is typing --> 
</datalist> 

您的search.php文件:

$term = $_GET['searchQuery']; 
$suggestions = []; 

if(isset($term) && !empty($term)){ 
    $servername = "your_db_servername"; // Ex: localhost 
    $username = "your_db_username"; // Ex: root 
    $password = "your_db_password"; 
    $dbname = "your_db_name"; 

    $conn = mysqli_connect($servername, $username, $password, $dbname); 
    if(!$conn) { 
     die("Connection failed: " . mysqli_connect_error()); 
    } 

    $sql = "SELECT Device_type FROM Device WHERE Device_type LIKE '". $term ."%';"; 
    $result = mysqli_query($conn, $sql); 

    if(mysqli_num_rows($result) > 0) { 
     while($row = mysqli_fetch_array($result)) { 
      array_push($suggestions, $row["Device_type"]); 
     } 
    } 

    mysqli_close($conn); 

    echo json_encode($suggestions); 
} 

但是你要注意,在埃維keyup事件發送AJAX請求可以是相當巨大特別是在用戶輸入速度快的情況下。

爲了使效率更高,最好去掉keyup事件。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js "></script> 
<script> 
$(document).ready(function() { 
    $('#searchbox').keyup($.debounce(250, function() { // act upon keyup events every 250 milliseconds when user is typing 
     $('#suggestions').html(''); 

     var input = $(this).val(); 

     $.getJSON(
      'search.php', 
      { searchQuery: input }, 
      function(data) { 
       $(data).each(function() { 
        var suggestion = '<option value=' + this + '>'; 
        $('#suggestions').append(suggestion); 
       }); 
      } 
     ); 
    })); 
}); 
</script> 
+0

感謝您的回覆。我無法找到'if(isset($ _ GET ['searchQuery'])&&!empty($ _ GET ['searchQuery'])){'在我的PHP文件中的正確位置。這對我來說很新穎,即使我已經有很多這樣的代碼已經從在線示例中整合在一起,所以其中一些我還沒完全理解。我更新了我的問題,提供了更多關於我的PHP文件的信息。我所做的每件事都沒有提供任何結果,或者仍然導致建議不可點擊。 – Jcmoney1010

+0

@ Jcmoney1010我用你需要的完整PHP代碼更新了答案。 –

+0

我很感謝您的詳細解答,但我似乎太密集,無法遵循簡單的說明。我已經嘗試將你的答案合併到我的代碼中,並且直接複製你的代碼並替換我的代碼,但我似乎無法得到任何工作。當我使用你提供的代碼時,我甚至沒有得到建議結果的下拉菜單。 – Jcmoney1010