自动建议ajax为PHP

时间:2012-05-09 16:29:04

标签: php jquery ajax autocomplete

我有一个html表单,php脚本和jquery。我需要一个ajax代码来自我的PHP脚本自动建议。以下是代码......

Form.html

  <html>
    <head>
      <script src="jquery1.6.4.min.js" type="text/javascript"></script>  
      <script src="jquery.jSuggest.js" type="text/javascript"></script>  
      <link href="jSuggest.css" rel="stylesheet" type="text/css" />  
     </head>  
     <body>  
       <form id="form1" name="form1" method="post" action="#">  
          <input type="text" name="TagsInputField" id="TagsInputField"/>  
        </form>  
      </body>  
  </html>  

TEST.php

  <?php 
      include("bc/script/core/dbcon.php");  
      $input = $_POST['TagsInputField'];  
      $data = array();  
      // query your DataBase here looking for a match to $input  
      $query = mysql_query("SELECT * FROM user WHERE username LIKE '%$input%'");  
      while ($row = mysql_fetch_assoc($query)) {  
        $json = array();  
        $json['value'] = $row['id'];  
        $json['name'] = $row['username'];  
        $data[] = $json;  
      }  
      header("Content-type: application/json");  
      echo json_encode($data);  
   ?>  

jquery.jSuggest.js

 $(function() {
    var dataSource = {
        items: [
            {
            value: "21",
            name: "Mick Jagger"},
        {
            value: "43",
            name: "Johnny Storm"},
        {
            value: "46",
            name: "Richard Hatch"},
        {
            value: "54",
            name: "Kelly Slater"},
        {
            value: "79",
            name: "Michael Jordan"}
        ]

    };

    $('#TagsInputField').jSuggest({
        source: dataSource.items,
        selectedItemProp: "name",
        seekVal: "name",
        selectionAdded: function(elem, data) {
            console.log(data.name);
        },
        selectionRemoved: function(elem, data) {
            console.log(data.name);
            elem.remove();
        }
    });
});

注意指针“source”它正在引用一个对象“dataSource.items”来读取建议。 任何人都可以帮我写一个ajax代码来读取fom php文件的回复json的建议。

1 个答案:

答案 0 :(得分:1)

jSuggest默认发出GET请求。你必须添加:

type: "POST"

在规则中。

您的jSuggest规则中还有一些其他重大错误。您应该阅读文档:http://scottreeddesign.com/project/jsuggest