簡體   English   中英

jQuery UI自動完成-多種來源

[英]Jquery ui autocomplete - multiple sources

對於1個源,這是ajax調用之后的正確代碼:url:“ links2.xml”,

我希望源是多個xml文件。 如何添加額外的路徑?

謝謝。

首先, 文檔說“自動完成插件希望該字符串指向將返回JSON數據的URL資源”。 注意:JSON,而不是XML,因此您需要在下面將xml轉換為json。

JSON格式的xml文件可以在您的服務器或客戶端瀏覽器上完成。 如果可能的話,在服務器上執行一次操作會更快。

要使用多個源文件,您需要首先在HTML / JS頁面中加載多個文件。 然后將它們連接到一個Javascript數組中,然后將該數組提供給autocomplete調用。

就像是:

<script>
  myproject_choices = []; // global var. Hence prefix with project name.

  var cb = function(data){jQuery.merge(myproject_choices, data);}; // callback for ajax

  $.getJSON('ajax/choices1.json', cb); // fetch and concatenate the choices
  $.getJSON('ajax/choices2.json', cb);
  $.getJSON('ajax/choices3.json', cb);
</script>

# later...
$( ".selector" ).autocomplete({source: myproject_choices });

我將任務分成

  1. 數據檢索
  2. 填充自動完成

如果您能夠從多個來源加載數據並使它們統一,則可以使用結果填充自動完成控件。 我建議您考慮使用jQuery Deferred對象(api.jquery.com/jQuery.Deferred)異步加載數據,並等待所有調用返回並使用$.when(...).then(...)

下面的示例來自寫得很好並且解釋得很好的網站: http : //www.danieldemmel.me/blog/2013/03/22/an-introduction-to-jquery-deferred-slash-promise/

function getReady() {
  var deferredReady = $.Deferred();
  $(document).ready(function() {
    deferredReady.resolve();
  });
  return deferredReady.promise();
}

var firstRequest = $.ajax({ url: 'http://www.html5rocks.com/en/tutorials/file/xhr2/' });
var secondRequest = $.ajax({ url: 'http://www.html5rocks.com/en/tutorials/audio/scheduling/' });

$.when( getReady(), firstRequest, secondRequest
).done( function( readyResponse, firstResponse, secondResponse ) {
  var insertDiv1 = $('<div></div>');
  insertDiv1.html($(firstResponse[0]).find('section').html());
  var insertDiv2 = $('<div></div>');
  insertDiv2.html($(secondResponse[0]).find('section').html());
  $('body').append(insertDiv1, '<hr/>', insertDiv2);
});

甚至有可能在jQuery方面這樣做嗎? 可能是您必須“手動”加載並加入文件。

我可以通過編寫自定義源函數來實現:

$("#elm").autocomplete({ source: function(request, response) {
$.ajax({
   url: "links1.xml",
   success: function(data)
   {
           // store data here
           $.ajax({
               url: "links2.xml",
               success: function(data)
               {  
                  // combine data from first call with this call
                  response(combineddata);
               }
           }
   });
}....

但是我已經可以在其他一些更好的方式合並文件。

具有自動完成功能的XML: http//jqueryui.com/demos/autocomplete/#xml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM