如何将额外的参数传递给Jquery自动完成字段? [英] How do I pass an extra parameter to Jquery Autocomplete field?

查看:69
本文介绍了如何将额外的参数传递给Jquery自动完成字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在其中一种表单中使用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.

这是我的表单的外观.

<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆