使用javascript预取加载外部数据集

时间:2014-07-20 08:41:55

标签: javascript datalist prefetch

您好我正在为我的网站中的搜索框构建自动完成功能。 我正在使用以下代码:

$(document).ready(function(){

var $terms = [ "aggretatibacter aphrophilus", "abiotrophia defectiva", "aerococcus viridans", "aggregatibacter actinomycetemcomitans", "aeromonas hydrophila", "aerococcus urinae", "actinobacillus ureae", "achromobacter xylosoxidans", "capnocytophaga gingivalis", "acinetobacter baumannii", "streptococcus pyogenes" ].sort(),
$return = [];

function strInArray(str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str) && $return.length < 5) {
  var $h = strArray[j].replace(str, '<strong>'+str+'</strong>');
  $return.push('<li class="prediction-item"><span class="prediction-text">' + $h + '</span></li>');
}
}
}

function nextItem(kp) {
  if ( $('.focus').length > 0 ) {
var $next = $('.focus').next(),
    $prev = $('.focus').prev();
}

if ( kp == 38 ) { // Up

if ( $('.focus').is(':first-child') ) {
  $prev = $('.prediction-item:last-child');
}

$('.prediction-item').removeClass('focus');
$prev.addClass('focus');

} else if ( kp == 40 ) { // Down

if ( $('.focus').is(':last-child') ) {
  $next = $('.prediction-item:first-child');
}

$('.prediction-item').removeClass('focus');
$next.addClass('focus');
}
}

$(function(){  
  $('#s').keydown(function(e){
$key = e.keyCode;
if ( $key == 38 || $key == 40 ) {
  nextItem($key);
  return;
}

setTimeout(function() {
  var $search = $('#s').val();
  $return = [];

  strInArray($search, $terms);

  if ( $search == '' || ! $('input').val ) {
    $('.output').html('').slideUp();
  } else {
    $('.output').html($return).slideDown();
  }

  $('.prediction-item').on('click', function(){
    $text = $(this).find('span').text();
    $('.output').slideUp(function(){
      $(this).html('');
    });
    $('#s').val($text);
  });

  $('.prediction-item:first-child').addClass('focus');

}, 50);
});
});

$('#s').focus(function(){
if ( $('.prediction-item').length > 0 ) {
  $('.output').slideDown();
}

$('#searchform').submit(function(e){
  e.preventDefault();
  $text = $('.focus').find('span').text();
  $('.output').slideUp();
  $('#s').val($text);
  $('input').blur();
  });
 });

 $('#s').blur(function(){
if ( $('.prediction-item').length > 0 ) {
  $('.output').slideUp();
}
});

});    

我想将另一个页面加载为datalist而不是:

   [ "aggretatibacter aphrophilus", "abiotrophia defectiva", "aerococcus viridans", "aggregatibacter actinomycetemcomitans", "aeromonas hydrophila", "aerococcus urinae", "actinobacillus ureae", "achromobacter xylosoxidans", "capnocytophaga gingivalis", "acinetobacter baumannii", "streptococcus pyogenes" ]

部分

但是最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

var $terms = [ "aggretatibacter aphrophilus", ... ].sort(),

可以使用jQuery getJSON从网址加载:

$.getJSON( "yourUrl", function( data )
{
  var $terms = [];

  $.each( data, function( val )
  {
    terms.push( val );
  }
  );

  terms.sort();
});