【问题标题】:extend the functionality for my AJAX database query扩展我的 AJAX 数据库查询的功能
【发布时间】:2014-04-17 20:22:58
【问题描述】:

您好,我正在处理以下与下拉列表一样工作的代码,我希望将下拉列表替换为具有数据库数据自动完成功能的文本框。

问题在于,对于下拉列表,代码中已经有硬编码选项可供选择,与文本框一样,它应该根据数据库值生成每个选项。

我不知道该怎么做,任何帮助都会很棒:)

这是我现在的代码:

HTML:

<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html> 

PHP

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','l3tm31n','records');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"records");
$sql="SELECT * FROM workers WHERE id = '".$q."'";

$result = mysqli_query($con,$sql);

echo "<table border='1'>
<tr>
<th>name</th>
<th>age</th>
<th>address</th>
<th>hasCar</th>
<th>speaksForeignLanguage</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['hasCar'] . "</td>";
echo "<td>" . $row['speaksForeignLanguage'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?> 

【问题讨论】:

  • 您想要动态填充的下拉列表或带有自动完成功能的文本框,例如 jqueryui.com/autocomplete
  • @HüseyinBABAL 我希望它有一个文本框,当您在文本框中键入时,该文本框会自动填充来自 mySQL 的数据。
  • 使用jquery自动补全可以吗?
  • @HüseyinBABAL 这完全没问题。

标签: php html mysql ajax


【解决方案1】:

将你的mysql查询改为

SELECT * FROM workers WHERE name LIKE '%$q%'

【讨论】:

    【解决方案2】:

    您可以使用 jquery autocomplete 做到这一点

    首先需要包含jquery

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    

    和 jquery ui

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
    

    然后创建你的文本框;

    <input type="text" name="names" value=""/>
    

    制作您的自动完成处理程序,

    <?php 
    $q = $_GET["q"];
    
    // Do your db connections
    
    $sql = "SELECT * FROM workers WHERE name = '%" . $q . "'%";
    
    $result = mysqli_query($con,$sql);
    
    $users = array();
    
    while($row = mysqli_fetch_array($result))
    {
        $users[] = $row;
    }
    
    mysqli_close($con);
    
    echo json_encode($users);
    
    
    ?> 
    

    在你的 js 中;

    $( "#names" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          type:"get",
          url: "getuser.php?q=" + request.term,
          success: function( data ) {
            response( $.map( data, function( user ) {
              return {
                label: user.name,
                value: user.id
              }
            }));
          }
        });
      },
      minLength: 1,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
    
        $.ajax({
            "url": "getuser.php?q=" + ui.item.id,
            "type": "get",
            success: function(response) {
                $("#txtHint").html(response);
            }
        });
      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });
    

    【讨论】:

    • 我尝试了你的建议,但似乎我在 firebug 上遇到了一个错误:SyntaxError: missing : after property id type="get",
    • @user3541335 对不起我的错误。应该是type:"get"。查看我的更新答案
    • 好的,错误消失了,但是当我在文本框中输入内容时没有任何反应。
    • 您在控制台上看到 ajax 请求了吗?
    • 没有控制台是空的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多