将结果从ajax合并到自动完成源

时间:2013-12-10 08:57:49

标签: jquery ajax

$(function() {
    $("#search").autocomplete({
        source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
    }).focus();

    $.ajax({
        url: "source.php",
        success: function(result) {
            return result;
            //["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
        }
    });

});

问题:如何使用ajax结果替换自动完成中的静态源?

点子:

$("#search").autocomplete({
    source: //result from ajax function
}).focus();

Source.php (仅举例)

<?php

mysql_connect('localhost', 'root', '');
mysql_select_db('test');

$query = mysql_query("SELECT name FROM tags");

while ($row = mysql_fetch_array($query)) {
    $results[] = $row['name'];
}

echo json_encode($results);
?>

3 个答案:

答案 0 :(得分:0)

我认为您需要连接两个数组(第一个单词列表和您通过ajax接收的单词列表),然后再次调用.autocomplete();

var words = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
$(function() {
    /** This part is only necessary if the ajax does not fire immediately when the page is loaded **/
    $("#search").autocomplete({
        source: words
    }).focus();
    /** end of what I said above **/
    $.ajax({
        url: "source.php",
       success: function(result) {
            words = words.concat(result);
            $("#search").autocomplete({
                source: words
            }).focus();
        }
    });

});

答案 1 :(得分:0)

1)声明全局数组变量并在需要时更改其值。

var languages = $.ajax({
        url: "source.php",
        success: function(result) {
            return result;
            //["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
        }
    });

$("#search").autocomplete({
        source: languages
    }).focus();

2)或合并ajax with autocomplete

$(function () {
    $("#city").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "source.php",
                success: function (data) {
                    return data;
                }
            });
        }
    });
});

答案 2 :(得分:0)

您应该使用两个参数来使用function as a source

$("#search").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "source.php",
            data: {query: request.term},
            success: function(result) {
                response(result);
            }
        });
    }
}).focus();

如果您键入&#34; php&#34;在该字段中,它将向source.php?query=php发出ajax请求。