2015-08-23 105 views
0

我有一个搜索框,使用PHP搜索电影数据库(查询数据库的电影标题,并从输入框中获取信息使用$ _POST)和jQuery(以立即搜索)。我希望它能够在输入框没有任何内容的情况下显示电影片名(目前显示)。PHP的jQuery检查输入框是否为空

这里是形式:

<form action="" method="post"> 

    <input type="text" autocomplete="off" name="search" placeholder="Search for movies or genres..." onkeyup="searchq();" /> 
    <input type="submit" value=">>" /> 
    <div id="outp"> 

    </div> 

</form> 

这里是jQuery的:

function searchq(){ 
    var searchTxt = $("input[name='search']").val(); 

    $.post("search.php", {searchVal: searchTxt}, function(out) { 
     $("#outp").html(out); 
    }) 
} 

这里是search.php中:

<?php 
include('db_con.php'); 

$out = ''; 

if (isset($_POST['searchVal'])){ 
    $searchq = $_POST['searchVal']; 
    $searchq = preg_replace("#[^0-9a-z\-]#i", "", $searchq); 

    $q = mysqli_query($con, "SELECT id, title FROM films WHERE title LIKE '%$searchq%'") or die("Could not search!"); 
    $c = mysqli_num_rows($q); 

    if ($c == 0){ 
     $out = '<p>There was no search results!</p>'; 
    } else { 
     while($line = mysqli_fetch_array($q)){ 
      $filmt = $line['title']; 
      $id = $line['id']; 

      $out .= '<div> <a href="list.php?id=' . $id . '">'.$filmt. '</a></div>'; 
     } 
    } 
} 

echo($out); 

?> 

我曾试图弥补没有电影标题出现在输入框中时什么也没有:

无论如何解决这个越来越呢?

谢谢。

回答

3

你应该修剪值,并检查它是否是一个空字符串触发Ajax请求之前:

function searchq(){ 
    var searchTxt = $("input[name='search']").val(); 
    if (searchTxt.trim() === "") { 
     $("#outp").html("<p>Please enter a query in the search input.</p>"); //Or any other message :) 
     return; 
    } 
    $.post("search.php", {searchVal: searchTxt}, function(out) { 
     $("#outp").html(out); 
    }) 
} 

而且情况下也加入了PHP脚本检查和形式没有js函数提交:

+0

谢谢 - 但是,而不是显示没有电影,这种修改显示最近的搜索电影? – Hp123

+0

确实,让我编辑我的答案,如果字符串为空,则应该用消息替换最新的搜索结果。 – taxicala

+1

谢谢!作品很棒:) – Hp123