【问题标题】:Autocomplete with bootstrap typeahead in google app engine在谷歌应用引擎中使用引导输入自动完成
【发布时间】:2012-10-30 07:30:10
【问题描述】:

我在 Google App Engine 应用程序中使用 Bootstrap typeahead,但它不起作用。

我的 HTML:

<div class="well">
  <input type="text" class="span3" id="search" name="search"
         data-provide="typeahead" data-items="4" />
</div>
<script>  
  $('#search').typeahead({
    ajax: { url: '/SearchCity', 
    triggerLength: 1 }
 });
</script>

还有我的 Python 代码:

class SearchCity(webapp2.RequestHandler):
    def post(self):
        data = ['cat','dog','bird', 'wolf']
        data = json.dumps(data)         
        self.response.out.write(data)

为什么自动完成功能不起作用?这段代码有什么问题?

【问题讨论】:

    标签: jquery python google-app-engine twitter-bootstrap bootstrap-typeahead


    【解决方案1】:

    typeahead 期望选项位于options 变量中。将您的视图转换为:

    class SearchCity(webapp2.RequestHandler):
        def post(self):
            data = ['cat','dog','bird', 'wolf']
            data = json.dumps({'options': data}) #Changed line
            self.response.out.write(data)
    

    另外,您的 HTML 可能需要一些更改,请尝试以下操作:

    $('#id_chain').typeahead({
      minLength: 1,
      source: function (query, process) {
        return $.get('/SearchCity', function (data) {
          return process(data.options);
        });
      }
    });
    

    这里的免责声明是您没有指定您正在使用的 Bootstrap 版本...这适用于框架的 v2+。

    【讨论】:

    • 非常感谢您的回答,但我收到“Uncaught TypeError: Cannot call method 'toLowerCase' of undefined”错误
    • 您能否为该错误提供一些上下文,可能是堆栈跟踪?您的脚本包含的顺序可能很糟糕,但如果没有更多信息就很难判断。
    • 我在 javascript 控制台收到此错误 Uncaught TypeError: Cannot call method 'toLowerCase' of undefined new.js:205 Typeahead.matcher new.js:205 (anonymous function) new.js:192 e .extend.grep jquery-1.7.1.min.js:2 Typeahead.lookup new.js:191 Typeahead.keyup new.js:302 g jquery-1.7.1.min.js:2 f.event.dispatch jquery- 1.7.1.min.js:3 h.handle.i
    • 从服务器获取数据成功了吗?换句话说,如果在return process(data.options); 行之前添加console.log(data);console.log(data.options);,你会得到什么?
    • 非常感谢您的解释,我已经通过在 SearchCity 中添加 self.response.headers['Content-Type'] = 'application/json' 解决了这个问题
    【解决方案2】:

    正如bootstrap's documentation 所说,这看起来更像:

    function get_data_async(query, callback) {
        $.ajax({
              url: '/SearchCity/',
              data: query,
              dataType: 'json',
              type: 'POST',
              success: callback
        })
    }
    
    $('#search').typeachead({source: get_data_async})
    

    【讨论】:

    • 非常感谢您的解释,我已经通过在 SearchCity 中添加self.response.headers['Content-Type'] = 'application/json' 解决了这个问题
    猜你喜欢
    • 2011-05-24
    • 2012-09-09
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多