2016-12-14 25 views
1

应该有一个输入文本框,如果用户写任何文本应该显示的客户名称搜索将使用Ajax的PHP下拉列表

<script> 
    function custlist() { 
     $.ajax({ 
      url: "custlist.php", 
      success: function(result) { 
       $("#customerlist").html(result); 
      }   
     }); 
    } 
    function showCustomers(str) { 
     $.ajax({ 
      type: "GET", 
      url: "customerlist.php", 
      data:'q='+str, 
      success: function(result) { 
       $("#customerlist").html(result); 
      }   
     }); 
    } 
</script> 

<input type="text" oninput="showCustomers(this.value)" placeholder="Search here" name="CustomerNo" /> 
<select name="Cno" id="customerlist" onfocus="custlist()"> 
    <option value="">Customer Name</option> 
</select> 

custlist.php的下拉列表

<?php 
    $sql2 = 'SELECT Customer_Name as Cname,No from customers order by Customer_Name'; 
    $result2 = mysqli_query($connection, $sql2); 

    if (mysqli_num_rows($result2) > 0) { ?> 
     <option value="">Customer Names</option>     
     <?php // output data of each row 
      while($row2 = mysqli_fetch_assoc($result2)) { ?> 
       <option value="<?php echo $row2['No']; ?>"><?php echo $row2["Cname"]; ?> 
       </option> 
     <?php } ?> 
<?php } ?> 

customerlist.php

<?php   
    $q = $_REQUEST["q"]; 
    // lookup all hints from array if $q is different from "" 
    if ($q !== "") { 
     $sql2 = "SELECT Customer_Name as Cname,No from customers where Customer_Name like '".$q."%s' order by Customer_Name"; 
     $result2 = mysqli_query($connection, $sql2); 

     if (mysqli_num_rows($result2) > 0) { ?> 
      <option value="">Customer Names</option>     
      <?php // output data of each row 
       while($row2 = mysqli_fetch_assoc($result2)) { ?> 
        <option value="<?php echo $row2['No']; ?>"><?php echo $row2["Cname"]; ?> 
        </option> 
      <?php } ?> 
    <?php } ?> 
<?php } ?> 

我在下拉菜单中获取数据,但我希望如果我在文本框中写入内容,则会自动显示与该字符匹配的下拉菜单。

还有一问题,我有...

第2期 - 当我输入“ABD”首先,它显示了启动与“ABD”客户名称,但自动显示开始“AB”下一个名字,然后“一个“然后是空的.. 这是为什么?

在此先感谢。

+1

你不应该在你的'.php'文件中打开和关闭你的PHP标签。只是回声的HTML而不是 –

回答

0

而不是 的Javascript:

$.ajax({ 
    type: "GET", 
    url: "customerlist.php", 
    data:'q='+str, 
    success: function(result){ 
     $("#customerlist").html(result); 
    } 
}); 

和PHP:

<?php 

$q = $_REQUEST["q"]; 

尝试这样做此Javascript:

$.ajax({ 
    type: "POST", 
    url: "customerlist.php", 
    data: {q: str}, 
    success: function(result){ 
     $("#customerlist").html(result); 
    } 
}); 

和PHP:

<?php 

$q = $_POST['q']; 

希望这有助于!

+1

我试过这个,但没有运气首先它给了正确的结果http://prntscr.com/dj9m8n然后像这样http://prntscr.com/dj9luj –

+0

我怎样才能合并文本框和下拉? –

+0

在您的customerlist.php中,您有以下行:我不认为这是有效的,因为在ajax调用中,您需要echo json_encode()所有结果并在jquery/javascript中使用它们 –