json使用json自动完成

时间:2010-07-28 23:02:25

标签: jquery json autocomplete

我尝试了很多东西,但我不明白这太令人困惑。

我有这个

<input id="wba" type="search" name="q" value="" class="search box" />
<input type="submit" value="Go" class="search button" />

也 一个php文件

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');

$arr = array('test'=>'hello world');

echo json_encode($arr);

至于javascript我已经尝试了一切,包括来自jquery网站的演示,但没有运气......那里有人帮我设置自动完成功能来显示数据?

修改

$(function() {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").attr("scrollTop", 0);
        }

        $("#wba").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "search.php",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function(data) {
                        response($.map(data.sites, function(item) {
                            alert(item);
                            window.console.debug(item);
                            return {

                                label: item.name ,
                                value: item.url
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                log(ui.item ? ("Selected: " + ui.item.name) : "Nothing selected, input was " + this.value);
            },
            open: function() {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function() {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });
    });

此代码来自jqueryui网站(演示)......

3 个答案:

答案 0 :(得分:1)

它应该是这样的

// JS
$(function() {
  $("#wba").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "search.php",
        dataType: "jsonp",
        data: { q: request.term },
        success: function(data) {
          response($.map(data, function(value,key) {
            return { label:value.label , value: value.val }
          }));
        }
      });
    },
    minLength: 2
  });
});​

// PHP
$results = array(
   array('label' =>'label1', 'val' => 'value1'),
   array('label' =>'label2', 'val' => 'value2'),
   array('label' =>'label3', 'val' => 'value3')
);
// Optionally do something with the user input ($_GET["input_value"])
echo $_GET['callback'].'('.json_encode($result).');'​​​​​​​​​

我不知道为什么但这确实有用......

答案 1 :(得分:0)

没有任何代码的基本前提是:

  • 在jQuery中,将事件侦听器绑定到输入,以便在用户键入内容时,调用一个函数
  • 然后该函数使用jQuery的ajax函数之一将输入值发送到php脚本
  • php脚本回显一个json编码的字符串
  • jquery ajax函数接收字符串
  • 然后该函数获取json数据并以某种程式化的方式将其附加到输入的外部
  • 每个选项都绑定了一个事件监听器,以便在单击某个选项时,会发生某些事情 - 输入中填充了单击的项目,运行了另一个函数,加载了页面等等。

有很多不同的方法可以实现这一点,这就是为什么我没有用实际功能回答的原因。这取决于你的目标。

答案 2 :(得分:0)

以下是我在服务器上使用C#实现它的方法。

<强>的JavaScript

function InitializeElement (element) {
    element.autocomplete("ServerPage.ashx", {
        formatItem: function(data) {
            return "<span style=\"font-size:9pt;word-break:break-all;\">" + data[0] + "<br />" + data[1] + "</span>";
        }
    });
    element.result(function(event, data, formatted) {
        jq(event.currentTarget).siblings('input[type=hidden]').val(data[2]);
        event.currentTarget.value = data[0];
        event.currentTarget.title = data[1];
    });
}

<强> C#

public class ServerPage : ApplicationHandler 
{ 
    protected override void Process()
    {
        String text = (this.Request.Params["q"] ?? String.Empty);

        if (text.Length > 0)
        {
            using (DatabaseRecords records = this.Core.Database.ExecuteRecords("StoredProcedure", new KeyValue("Text", text)))
            {
                while (records.Read())
                {
                    Response.Write(records.GetString("Code") + "|" + records.GetString("Description") + "|" + records.GetInt32("Id") + "\n");   
                }   
            }
        }       
    }
}