【问题标题】:How to fetch data from MySQL database and use in a javascript autocomplete?如何从 MySQL 数据库中获取数据并在 javascript 自动完成中使用?
【发布时间】:2018-10-23 14:08:31
【问题描述】:

我正在使用 jQuery autocomplete 构建自动完成功能。为此,我在一个表中存储了 216 个行业的数据记录。我想获取该表并在 javascript 数组中用于自动完成。你可以看到我到目前为止所做的尝试,但我得到了空值。我的问题是如何从数据库中获取数据并使其成为可以在 javascript 数组中用于自动完成的数组?

表格

id | industryName
1  | Air Transport
2  | Agriculture
...

autocomplete.php

<div class="ui-widget">
  <label for="industries">Industries: </label>
  <input id="industries">
</div>

<script>
        $.ajax({
           url : 'industries.php',
           type : 'GET',
           success : function(data){
              var availableIndustries = jQuery.parseJSON(data);

        $( function() {
        $( "#industries" ).autocomplete({
          source: availableIndustries
        });
      } );
           }
        });
</script>

industries.php

include 'includes/database.php';

 $sql = "SELECT * FROM industries";
 $result= $conn->query($sql);
 echo json_encode($result);

【问题讨论】:

  • 错误是什么?
  • 你还记得实际包含 jQuery 和 jQueryUI 吗?
  • 应该是source: 'industries.php', here's an example
  • @Richard :这是我在运行 industries.php 时看到的:{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
  • @ObsidianAge:刚刚验证过,是的,一切都在那里。我在日历的不同页面上使用 jquery,它工作正常。

标签: javascript php jquery autocomplete


【解决方案1】:

你的命名对吗?例子是错误的..

另外,在echo json_encode($result); 之后添加和exit;

【讨论】:

  • 这是一个拼写错误。对不起。我试图用一个while语句来显示它并且它有效。所以json不能正常工作。
  • 所以您使用的是GET,当您直接浏览该网址时会看到什么?
  • 你的意思是当我输入 localhost/myProject/industries.php 时?如果有while($data = mysqli_fetch_array($result)){ echo $data['Industry']; }json_encode($result) 的while 语句,我会看到所有记录,我看到{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} 。否则它是一个空白页。
【解决方案2】:

我找到了适合我的解决方案。

autocomplete.php

<div class="ui-widget">
  <label for="industries">Industries: </label>
  <input id="industries">
</div>

<script>
var validOptions = <?=$json_array?>;
previousValue = "";

$('#industries').autocomplete({
    autoFocus: true,
    source: validOptions
}).keyup(function() {
    var isValid = false;
    for (i in validOptions) {
        if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }
});
</script>

industries.php

//bind to $name
if ($stmt = $conn->prepare("SELECT Industry FROM industries")) {
    $stmt->bind_result($name);
    $OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
    $result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2011-07-30
    • 2011-05-06
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多