如何将额外的参数传递给 Jquery 自动完成字段? [英] How do I pass an extra parameter to Jquery Autocomplete field?
问题描述
我在其中一个表单中使用了 JQuery 自动完成功能.
I'm using the JQuery Autocomplete in one of my forms.
基本表单从我的数据库中选择产品.这很好用,但我想进一步开发,以便只返回从某个邮政编码发货的产品.我已经弄清楚了后端脚本.我只需要找出将邮政编码传递给此脚本的最佳方式.
The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.
这就是我的表单的样子.
This is how my form looks.
<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 代码:
And here is the JQuery code:
$("#product").autocomplete
({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){
//action
}
});
此代码在一定程度上有效.但无论实际选择哪个值,都只返回第一个邮政编码值.我猜发生的事情是源 URL 在页面加载时启动,而不是在选择菜单更改时启动.有没有解决的办法?或者有没有更好的方法来达到我所追求的结果?
This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?
推荐答案
您需要对 source
调用使用不同的方法,如下所示:
You need to use a different approach for the source
call, like this:
$("#product").autocomplete({
source: function(request, response) {
$.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() },
response);
},
minLength: 2,
select: function(event, ui){
//action
}
});
这种格式允许您在运行时传递任何值,而不是在绑定时.
This format lets you pass whatever the value is when it's run, as opposed to when it's bound.
这篇关于如何将额外的参数传递给 Jquery 自动完成字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!