我完全是个 jQuery 菜鸟,需要创建一个使用 jQuery 自动完成功能的表单。我不想开始更大的项目,而是想继续并完成示例 here ,其中练习的重点是从 MySQL 表(在本例中为我的机器本地)中提取自动完成数据。我的 JS 和 HTML 代码是:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<!-- Here is the jQuery code -->
<script>
$(function() {
$('#abbrev').val("");
$("#state").autocomplete({
source: "states.pl",
minLength: 2,
select: function(event, ui) {
$('#state_id').val(ui.item.id);
$('#abbrev').val(ui.item.abbrev);
}
});
});
</script>
<!-- The HTML is simplistic for the example: -->
<form method="post">
<fieldset>
<legend>jQuery UI Autocomplete Example - PHP Backend</legend>
<p>Start typing the name of a state or territory of the United States</p>
<p class="ui-widget"><label for="state">State (abbreviation in separate field): </label>
<input type="text" id="state" name="state" /> <input readonly="readonly" type="text" id="abbrev" name="abbrev" maxlength="2" size="2"/></p>
<input type="hidden" id="state_id" name="state_id" />
<p><input type="submit" name="submit" value="Submit" /></p>
</fieldset>
</form>
<script>
$("#autocompleteForm").submit(function(){
$("#submitted").html("State: " + $("#state").val() + "<br />State Abbreviation: " + $("#abbrev").val() + "<br />State ID: " + $("#state_id").val());
return false;
});
</script>
我的 Perl 脚本是
#!/usr/local/bin/perl
# PERL MODULES WE WILL BE USING
use CGI;
use DBI;
use DBD::mysql;
use JSON;
# HTTP HEADER
print "Content-type: application/json; charset=iso-8859-1\n\n";
# CONFIG VARIABLES
my $platform = "mysql";
my $database = "us";
my $host = "localhost";
my $port = "3306";
my $tablename = "states";
my $user = "user";
my $pw = "pass";
my $cgi = CGI->new();
my $term = $cgi->param('term');
# DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";
# PERL DBI CONNECT
$connect = DBI->connect($dsn, $user, $pw);
# PREPARE THE QUERY
$query_handle = $connect->prepare(qq{select id, trim(both char(13) from state) AS value, abbrev FROM states where state like ?;});
# EXECUTE THE QUERY
$query_handle->execute('%'.$term.'%');
# LOOP THROUGH RESULTS
while ( my $row = $query_handle->fetchrow_hashref ){
push @query_output, $row;
}
# CLOSE THE DATABASE CONNECTION
$connect->disconnect();
# JSON OUTPUT
print JSON::to_json(\@query_output);
我单独调用了 Perl 脚本,我得到了格式正确的结果(即状态和缩写列表)。但是,当我运行该示例时,我没有得到自动完成结果。我究竟做错了什么? states.pl
位于同一个文件夹中,所以我相信我的脚本正在被 HTML 调用,但我不知道它给出了 jQuery 期望的响应。
最佳答案
我发布这篇文章是为了防止其他人和我一样感到沮丧。我终于想通了,解决方法是在perl脚本返回的hash ref中指定ID,这样以JSON格式传递给JS代码的实际上是一个字符串数组。
while ( my $row = $query_handle->fetchrow_hashref ){
push @query_output, $row->{'id'};
}
一如既往,调试永远不会令人满意。不过,我发现 Chrome 的调试工具非常有用。
关于jquery - 为什么我的 jQuery 自动完成代码会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8127210/