如何将额外的parameter passing给Jquery自动填充字段?

我在我的一个表单中使用了JQuery Autocomplete。

基本forms从我的数据库中select产品。 这很好,但我想进一步发展,只有从某个邮政编码发货的产品返回。 我已经find了后端脚本。 我只需要制定将邮政编码传递给此脚本的最佳方法。

这是我的表单看起来的样子。

<form> <select id="zipcode"> <option value="2000">2000</option> <option value="3000">3000</option> <option value="4000">4000</option> </select> <input type="text" id="product"/> <input type="submit"/> </form> 

这里是JQuery代码:

 $("#product").autocomplete ({ source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&", minLength: 2, select: function(event, ui){ //action } }); 

这个代码在一定程度上起作用。 但只返回第一个邮政编码值,不pipe实际select哪个值。 我想现在发生的事情是,源URL是在页面加载时启动的,而不是当select菜单被改变时。 有没有解决的办法? 还是有一个更好的方式来实现我所追求的结果?

您需要为source调用使用不同的方法,如下所示:

 $("#product").autocomplete({ source: function(request, response) { $.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() }, response); }, minLength: 2, select: function(event, ui){ //action } }); 

这种格式可以让你在运行时传递任何值,而不是绑定时的值

这不是复杂的男人:

 $(document).ready(function() { src = 'http://domain.com/index.php'; // Load the cities straight from the server, passing the country as an extra param $("#city_id").autocomplete({ source: function(request, response) { $.ajax({ url: src, dataType: "json", data: { term : request.term, country_id : $("#country_id").val() }, success: function(data) { response(data); } }); }, min_length: 3, delay: 300 }); }); 

我相信你认为你的调用是正确的$("#product").autocomplete在页面加载时触发。 也许你可以给select菜单分配一个onchange()处理程序:

 $("#zipcode").change(resetAutocomplete); 

并使其#product autocomplete()调用失效,并创build一个新的。

 function resetAutocomplete() { $("#product").autocomplete("destroy"); $("#product").autocomplete({ source:"product_auto_complete.php?postcode=" + $('#zipcode').val(), minLength: 2, select: function(event, ui){... } }); } 

您可能希望您的resetAutocomplete()调用变得更智能一些,比如检查邮政编码是否与上一个值实际不同,以节省一些服务器调用。

这为我工作。 覆盖事件search

 jQuery('#Distribuidor_provincia_nombre').autocomplete({ 'minLength':0, 'search':function(event,ui){ var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val(); $(this).autocomplete("option","source",newUrl) }, 'source':[] }); 
 jQuery("#whatJob").autocomplete(ajaxURL,{ width: 260, matchContains: true, selectFirst: false, minChars: 2, extraParams: { //to pass extra parameter in ajax file. "auto_dealer": "yes", }, }); 
 $('#product').setOptions({ extraParams: { extra_parameter_name_to_send: function(){ return $("#source_of_extra_parameter_name").val(); } } }) 
 $('#txtCropname').autocomplete('Handler/CropSearch.ashx', { extraParams: { test: 'new' } });