【问题标题】:jqueryui autocomplete with ajax response带有ajax响应的jqueryui自动完成
【发布时间】:2012-07-31 17:44:33
【问题描述】:

我试图在 ajax 中获得对 JqueryUi 自动完成的响应,但我无法在下拉框中得到结果。这是脚本=>

$(function(){
    $("#user_key" ).autocomplete({
        source: function(){
            var http = false;
            if (window.XMLHttpRequest){
                http = new XMLHttpRequest();
            } else {
                http = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (http){
                http.open("POST","./ajax/autocomplete.php",true);
                http.onreadystatechange = function(){
                    if (http.status==200 && http.readyState==4){
                        this.value = http.responseText;
                    }
                };
                http.send(null);
            }
        },
        close: function(){

        }
    });
});

为了简化autocomplete.php 中的示例,仅写为<?php echo "hello"; ?> 我怎样才能在下拉框中得到这个“你好”,为什么需要在脚本底部使用 close: 函数,谢谢 :)

附言。我认为我在编写 this.value = http.responseText 时犯了错误,例如在编写 alert(http.responseText) 时,它会从 .php 文件中获取结果。如何在下拉框中指明结果?

【问题讨论】:

  • 如果您使用 jQuery,请使用 $.post() 或 $.ajax() 方法进行 AJAX。
  • 事实是我不知道来自 Jquery 的 Ajax,因为我有这样的脚本
  • 具体请阅读有关remote sources的文档。
  • 使用您不理解的语言、框架或库进行编程通常是个坏主意。

标签: php ajax autocomplete


【解决方案1】:

根据文档和我所做的一些测试,您只需将source 属性设置为您的php 脚本的url。

jQuery UI 代码将查询字符串中的 term 参数发送到您在此处指定的 url:source.php?term=hello

因此,在您的示例中,假设您在 PHP 脚本中正确处理了查询字符串参数,该参数应该返回一个 JSON 数组。

$(function(){
    $("#user_key" ).autocomplete({
        source: "./ajax/autocomplete.php",
        minLength: 2
    });
});

返回的 JSON 数据应具有以下格式:

[{ "id" : "Item1", "label" : "Item1", "value" : "Item1" }, 
{ "id": "Item2", "label" : "Item2", "value" : "Item2" }]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 2012-10-08
    • 2014-09-12
    • 2017-12-07
    • 2010-10-14
    相关资源
    最近更新 更多