1

I am unable to get the prefetch option to work in typeahead.js. Local data works fine. Answers to previously posted questions suggest that caching could be an issue, but I have set the ttl to 0 and am testing in private browsing mode in Firefox and Chrome. What am I missing?

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="http://twitter.github.com/typeahead.js/releases/latest/typeahead.css">
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://twitter.github.com/typeahead.js/releases/latest/typeahead.js"></script>
</head>

<script type="text/javascript">
$(document).ready(function(){
  $('#searchText').typeahead([
    {
      name: 'terms',
      //local: ["United States", "Canada"],
      prefetch: 'http://twitter.github.io/typeahead.js/data/countries.json',
      ttl: 0
      }
    ]);
  });
</script>

<body>
<div class="container">
  <input class="typeahead" type="text" id="searchText">
</div>
</body>

</html>
4

1 回答 1

1

当某些东西“不工作”时,您应该始终检查console(Firebug / Chrome 开发工具),这是您使用 JS 时最好的朋友。

在这种情况下,并不是说prefetch不起作用。但是 Github 不允许您从不同的域中获取该 json。如果你检查你的控制台,你会看到这个错误:

XMLHttpRequest cannot load http://twitter.github.io/typeahead.js/data/countries.json. Origin http://yourdomain is not allowed by Access-Control-Allow-Origin.

因此,如果您想让这个示例在本地工作,您应该下载该 JSON 文件并在本地进行设置,然后将 URL 更改为如下所示:

$(document).ready(function(){
    $('#searchText').typeahead({
        name: 'terms',
        prefetch: '/data/countries.json', // go to http//yourdomain/data/countries to make sure the path is correct
        ttl: 0
    });
});

希望能帮助到你。

于 2013-08-09T10:41:43.313 回答