【发布时间】:2011-04-17 20:53:41
【问题描述】:
我正在尝试使用 jquery 自动完成功能设置输入标签,但是当我引用外部 JSON 数据时它不起作用。但是,它可以完美地使用本地类似 JSON 的数组......让我在我的代码中解释一下:
HTML 文件:
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#birds").autocomplete({
source: "http://localhost:3000/autocomplete_searches/index.json",
minLength: 3
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" />
</div>
</body>
</html>
我的 Rails 应用中的 autocomplete_searches_controller.rb
class AutocompleteSearchesController < ApplicationController
def index
@tags = Tag.limit(30).name_like(params[:term])
@tags_hash = []
@tags.each do |tag|
@tags_hash << {"label" => tag.label}
end
render :json => @tags_hash
end
end
仅此 JSON 操作就可以很好地工作,例如: http://localhost:3000/autocomplete_searches/index?term=psychiatric 给我:
[{"label":"Psychiatric Hospital"},{"label":"Psychiatric Nurse"},{"label":"Psychiatric Examination"}]
我可以看到我的 jQuery 函数也在以某种方式工作,因为当我在我的#birds 输入框输入例如“italy”时,WEBrick 给了我:
Started GET "/autocomplete_searches/index.json?term=italy" for 127.0.0.1 at 2010-09-27 18:07:07 +0200
Processing by AutocompleteSearchesController#index as JSON
Parameteres: {"term"=>"italy"}
bla bla bla SELECT "tags".* FROM "tags" WHERE (tags.name LIKE '%italy%') LIMIT 30
但我在网站上看不到任何影响。正如我所说,当我将相同格式的数据直接放在我的 html 文件中时,自动完成脚本工作得很好。在这个我没有遇到任何问题:
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#birds").autocomplete({
source: [{"label":"Psychiatric Hospital"},{"label":"Psychiatric Nurse"},{"label":"Psychiatric Examination"}],
minLength: 3
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" />
</div>
</body>
</html>
那么问题出在哪里?我是 JSON 新手,所以也许我做错了什么。
【问题讨论】:
-
如果将源更改为相对 url 有帮助吗?例如- /autocomplete_searches/index.json.
标签: jquery ruby-on-rails json jquery-ui autocomplete