2010-10-25 52 views

回答

0

它甚至有可能做到这一点的jQuery的一面?可能是你必须加载和“手动”加入文件。

+0

我已经用1个xml文件做它为什么我不能再发出第二个请求?我知道我可以请求所有文档,然后将它们解析在一起,然后将其传递给jquery,但是额外的步骤会像浪费时间一样接缝。我宁愿只做2个独立的源请求。 – specked 2010-10-25 20:40:15

+0

可能是jQuery _has_实现了使用2个文件作为源的功能,或者可能是_not_。据我所知,它没有这个功能,所以你必须自己做。另一种方法是在服务器端,你不能只加入文件吗? – joni 2010-10-25 20:43:49

1

首先,docs表示“自动填充插件期望该字符串指向将返回JSON数据的URL资源。” 注意:JSON,而不是XML所以你需要在下面将你的xml转换成json。

xml to json可以在您的服务器上或客户端浏览器上完成。如果可能的话,在服务器上执行一次操作会更快。

要使用多个源文件,您需要首先在HTML/JS页面中加载多个文件。然后将它们连接在一起成为一个Javascript数组,然后将该数组提供给自动完成调用。

喜欢的东西:

<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 }); 
0

我可能可以通过编写自定义源功能:

$("#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

+0

@Larry K:xml可以被解析为可用于“respone()”的对象数组。每个对象都有一个id,value,label和both属性。 – Milo 2010-10-25 20:56:24

+0

@Larry K: 如果来源不是静态的,你的解决方案可以工作,但可能不是一个有效的解决方案。 – Milo 2010-10-25 21:01:21

+0

OP通过一个url使用静态源代码。 – 2010-10-25 21:29:20

0

我想如果你能够从加载数据的任务分成

  1. 数据的检索
  2. 填充自动完成

多个来源并统一它们,您可以使用结果来填充自动完成控件。我建议你看看使用jQuery Deferred-objects(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); 
}); 
相关问题