【问题标题】:jQuery UI Autocomplete with a JSON datasource generated from Rails - not working带有从 Rails 生成的 JSON 数据源的 jQuery UI 自动完成 - 不工作
【发布时间】: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


【解决方案1】:

Ee... 我在 Rails 中做了一个新动作,并将这个 html 代码作为视图。它开始起作用了。但是为什么它是一个独立的 html 文件时我不能让它工作呢?

【讨论】:

    【解决方案2】:

    这有点摸不着头脑,但您是否正在运行 jQuery Validator 插件?在其最新版本中,我在干扰我的 AJAX 操作时遇到了一些麻烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2015-10-18
      • 2012-08-04
      • 1970-01-01
      相关资源
      最近更新 更多