【问题标题】:Typeahead.js not showing dropdownTypeahead.js 不显示下拉菜单
【发布时间】:2014-02-07 20:47:58
【问题描述】:

我正在使用dataType:'jsonp'从远程位置获取源代码,如果我在 chrome 上看到开发人员工具,我会收到包含某些数据的响应,但预输入的下拉菜单从未出现。

这是我正在使用的代码:

$(document).ready(function(){
$('#txtMedicamentos').typeahead({
    header:'<b>Medicamentos</b>',
    template:['<span>{{descripcionMedicamento}}</span>'].join(''),
    limit:10,
    minLength: 3,
    remote:{
        url:'http://geofarma.pe/service/GetMedicamentos/%QUERY',
        filter: function(parsedResponse){
            console.log(parsedResponse);
            for (i = 0; i < parsedResponse.length; i++) {
                parsedResponse[i].value = parsedResponse[i].descripcionMedicamento;
                parsedResponse[i].tokens = new Array(parsedResponse[i].descripcionMedicamento);
            }
            return parsedResponse;
        },
        dataType: 'jsonp'
    },
    engine:Hogan
});
});

演示:http://jsfiddle.net/XtLrH/

【问题讨论】:

  • 这样的东西有用吗? jsfiddle.net/trevordowdle/XtLrH/2 使用以下小提琴作为参考.. jsfiddle.net/Sherbrow/p3wXs
  • 有一次在使用 typeahead.js 时,我遇到了一个类似的问题,即窗口无法打开 - 原来这是一个 CSS 问题。如果下拉菜单显示为元素,请尝试检查 Chrome 调试器。
  • 您解决了这个问题吗?正如我在回答中所说,这是一个跨域问题。

标签: javascript jquery ajax jsonp typeahead.js


【解决方案1】:

我通过首先分支和修改你的 jsfiddle 来调查这个问题:

http://jsfiddle.net/Fresh/gYFDV/

当我运行此示例时,我遇到了您的问题,即即使远程请求返回有效的 JSON 数据,下拉菜单也不显示搜索结果。

当我搜索“TEST”时,我可以在浏览器控制台中看到返回的结果(在本例中为两条记录):

0: {codigoMedicamento:16858, descripcionMedicamento:TESTOVIRON DEPOT 250mg/mL Inyectable,…}
1: {codigoMedicamento:17091, descripcionMedicamento:TESTONON Inyectable,…}

但是,问题在于您的服务器返回的数据包含错误的 JSONP 请求响应标头:

Content-Type:application/json

由于这是一个跨域请求并且您正在返回 JSONP 数据,您应该将响应标头更改为:

Content-Type:application/javascript

(请参阅here 了解更多信息)

此外,完整的响应标头如下所示:

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Language:es-PE
Content-Type:application/json
Date:Thu, 23 Jan 2014 00:00:00 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=100
Pragma:no-cache
Server:Apache
Transfer-Encoding:chunked

看起来也不正确的是“Expires”值;据此,响应数据于 1981 年到期!

因此,要解决此问题,您似乎需要修改服务调用(即http://geofarma.pe/service/GetMedicamentos),以便它在其响应标头中返回正确的 Content-Type。将 Expires 值设置为更新的值也是一个好主意。

【讨论】:

    【解决方案2】:

    由于您的请求是JSONP,您需要在您的网络服务器中处理jQuery添加的回调。

    我尝试从您的网络服务器获取 JSONP,就像 jQuery 一样:

    http://geofarma.pe/service/GetMedicamentos/QUERY?callback=jQuery2101169277074432582543968319604650201646145433_1390418575420&_=1390418575421

    似乎网络服务器没有处理 JSONP 回调,所以 jQuery 没有得到预期的响应。

    另外,如果您的前端和后端使用不同的域,您需要更改 JSONP 响应中的 Access-Control-Allow-Origin 标头。

    【讨论】:

    猜你喜欢
    • 2019-08-25
    • 2012-05-27
    • 2022-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    相关资源
    最近更新 更多