为什么$("#tags")。自动完成不能处理来自PHP的数据?

时间:2014-05-04 19:33:40

标签: php jquery autocomplete

  <script>
  <?php
    mysql_connect('127.0.0.1', 'root', '') or die(mysql_error());
    mysql_select_db("Project_Part1")or die("cannot select DB");
    $sqlActivity = "SELECT aname FROM Activity";
    $resultActivity=mysql_query($sqlActivity);
    $aname = array();
    while ($row = mysql_fetch_array($resultActivity)) {
      $aname[] = $row;
   }    
  ?>
  $(function() {
        var availableTags =[ "<?php echo implode('","',$aname);?>" ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
  </script>
<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" />
</div>

不确定原因 var availableTags =[ "<?php echo implode('","',$aname);?>" ];  不适用于自动完成。 当我使用var availableTags = [ "Rock climbing","Fishing","Kayaking","Underwater bungee jumping" ];时很好。

我是PHP的新手。任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:1)

尝试:

<?php
    $DBi   = mysqli_connect($hostname, $user, $password, $database);
    $aname = array();

    $sqlActivity = "SELECT `aname` FROM `Activity`";
    $resultActivity = mysqli_query($DBi, $sqlActivity);   //Dump mysql_query for 
                                                          //mysqli_query and don't 
                                                          //forget the connection bit
    while ($row = mysqli_fetch_array($resultActivity)) {
        $aname[] = $row;
    };    
?>

<script>
    $(function() {
        var availableTags =[ "<?php echo implode('","',$aname);?>" ];
        $("#tags").autocomplete({
            source: availableTags
        });
    });
</script>

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" />
</div>

您的<?php标记后面似乎缺少<script>。我将PHP SQL位移到了<script>标记之外(这应该无关紧要,但确实有助于让我的内容更容易阅读)

当你在这里时,停止使用mysql_并切换到mysqli_ functions,因为前者已被弃用