简体   繁体   中英

Typeahead.js prefetch option not working

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>

You should always check the console (Firebug / Chrome dev tools) when something is "not working", it's your best friend when working with JS.

In this case, it's not that prefetch is not working. But Github doesn't allow you to fetch that json from different domain. If you check your console, you will see this error:

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

So if you want to get this example working locally, you should download that JSON file and set it up locally, then change the URL a bit like:

$(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
    });
});

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM