jQuery Autocomplete 使用 extraParams 传递额外的 GET 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2727859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:10:10  来源:igfitidea点击:

jQuery Autocomplete using extraParams to pass additional GET variables

jqueryjquery-pluginsjquery-autocompleteautosuggest

提问by paperclip

I am referring specifically to the jQuery Autocomplete v1.1 plugin by J?rn Zaefferer [source: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/]as there seems to be quite a few variations of this plugin.

我指的是 J?rn Zaefferer [来源:http: //bassistance.de/jquery-plugins/jquery-plugin-autocomplete/]的 jQuery Autocomplete v1.1 插件,因为这似乎有很多变体插入。

I'm trying to pass additional parameters to the server when the user starts typing because I have multiple fields that I want autocomplete to provide suggestions for.

当用户开始输入时,我试图将其他参数传递给服务器,因为我有多个字段需要自动完成以提供建议。

In addition to the query, I want to send the input name attribute to the server but I can't seem to use $(this).attr('name') within the extraParams.

除了查询之外,我想将输入名称属性发送到服务器,但我似乎无法在 extraParams 中使用 $(this).attr('name') 。

My jQuery:

我的jQuery:

   $('.ajax-auto input').autocomplete('search.php', {
     extraParams: {
      search_type: function(){
       return $(this).attr('name');
      }
     }
   })

This is my HTML.

这是我的 HTML。

 <form method="post" action="#" id="update-form" autocomplete="off">
  <ol>
         <li class="ajax-auto">
             <label for="form-initials">Initials</label>
                <input type="text" id="form-initials" name="initials" />
            </li>
         <li class="ajax-auto">
             <label for="form-company">Company</label>
                <input type="text" id="form-company" name="company" />
            </li>
  </ol>
 </form>

Any suggestions?

有什么建议?

回答by ramonhimera

I am using the autocomplete function that is now part of jquery ui. Passing an 'extraParams' field does not work but you can just append the values in the request query string.

我正在使用现在是 jquery ui 一部分的自动完成功能。传递“extraParams”字段不起作用,但您可以只在请求查询字符串中附加值。

$(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
    });
});

回答by Nam Le

Try this:

尝试这个:

$('.ajax-auto input').setOptions({
  extraParams: {
    search_type: function(){
      return $(this).attr('name');
    }
  }
})

See also here

另见此处

回答by Dan Csharpster

You can use the built in jquery ui autocomplete like so:

您可以像这样使用内置的 jquery ui 自动完成功能:

          $(function() {
         $("#BurroughName").autocomplete({
                minLength: 0,
                source: function( request, response) {
                            $.ajax({
                                        url: "/JsonData/GetBurroughFromSearchTermJson",
                                        dataType: "json",
                                        data: {
                                                    term: request.term,
                                                    CityId: $("#CityId").val()
                                        },
                                        success: function( data ) {
                                                    response( data );
                                        }
                            });
                },                  
                select: function( event, ui) {
                    $("#BurroughId").val(ui.item.id);

                    if (ui.item.id != null) {
                         var cityId = $('#CityId').val();
                        $.getJSON("/AdSales/City.mvc/GetCityJSONListFromBrand", { burroughId: ui.item.id }, function(data) {
                             $("#CityId").fillSelect(data);
                             var foo = $("#CityId option[value=" + cityId + "]");
                             if(($("#CityId option[value=" + cityId + "]").length > 0) && cityId != "")
                             {
                                 $("#CityId").val(cityId);
                             }
                        });
                    }
                    $('#burroughSpinner').fadeOut('slow', function(){});
                }
         });
     });

Here's their jsonp example: http://jqueryui.com/demos/autocomplete/#remote-jsonp

这是他们的 jsonp 示例:http: //jqueryui.com/demos/autocomplete/#remote-jsonp

回答by farness

I had a similar Problem... don't know if it will work for you ....

我有一个类似的问题......不知道它是否适合你......

I Tried

我试过

 $("#awbCusName").autocomplete("getOracleCus.php?",{
  extraParams: {
  ZONE: function() { return $("#awbZone").val(); }, 
  SE: function() { return $("#awbSE").val(); }, 
  WSC: function() { return $("#awbWSC").val(); } 
 },
delay:200,
selectOnly:true,
cacheLength:0,
autoFill:true,
matchSubset:true,
minChars:1
});

CACHELENGTH:0 did the trick

CACHELENGTH:0 成功了

Thanks

谢谢

回答by jszoja

jQuery( "#jac" ).autocomplete({
    source: autocompleteURL,
    minLength: 2,
    search: function( event, ui ) { 

        // update source url by adding new GET params
        $(this).autocomplete( 'option', 'source', autocompleteURL + 'var1=aaa&var2=bbb' );
    }
})

Works for me with jquery.ui.autocomplete 1.8.17

使用 jquery.ui.autocomplete 1.8.17 对我有用

回答by avoidingwork

Using the autocomplete in JQuery 1.7.something...

在 JQuery 1.7.something 中使用自动完成...

Using an aspx data grid: I needed autocomplete to fire for any record choosen but with different seed data based on the value entered. I also needed two other fields that are being displayed in the record on the data grid to get my data for the autocomplete. The fields I need to reference all have their own class name.

使用 aspx 数据网格:我需要自动完成来触发任何选择的记录,但根据输入的值使用不同的种子数据。我还需要在数据网格的记录中显示的另外两个字段来获取我的自动完成数据。我需要引用的字段都有自己的类名。

    $(".AutoSearch").autocomplete({
            DateTime: "",
            Maker: "",
            search: function (event, ui) {
                DateTime = $(this).parent().parent().parent().find(".DateTime").text();
                Maker = $(this).parent().parent().parent().find(".Maker").text();
            },
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "AutoList.aspx/GetListOfAutos",
                    data: "{ " +
                        "'DateTime': '" + DateTime + "', " +
                        "'Maker': '" + Maker + "', " +
                        "'SearchSeed': '" + request.term + "', " +
                        "'NumberToRetrieve': '" + 100 + "'" +
                    " }",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.Description,
                                value: item.Number
                            }
                        }));
                    },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("There was an error retrieving the Data.");
                    }
                });
            },
            change: function (event, ui) {
                $(this).parent().parent().parent().parent().parent().parent().css("background-color", "#EEC900");
                $(this).parent().parent().parent().parent().parent().parent().find(".chkReadyExport").find("input:checkbox").prop("checked", false);
            },
            select: function (event, ui) {
                this.value = ui.item.value;
                return false;
            },
            minlength: 6,
            open: function () {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function () {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });
    }

I added two properties; DateTime and Maker and then using search: which is fired before the autocomplete fires source: I was able to get the data I needed from the row that I was on. This provided me a nice way to keep all my searching and extra data items all in one place.

我添加了两个属性;DateTime 和 Maker 然后使用 search: 在自动完成触发源之前触发:我能够从我所在的行中获取我需要的数据。这为我提供了一种将所有搜索和额外数据项都保存在一个地方的好方法。

The .parent().parent() and so on is because I have multi-line tables to display my data in the gridview and I need to traverse up the tree and then find the text box or label I'm looking for and change the background color of the row with the changed data. I am not proficient at finding items with jQuery yet thus the parent.parent... thing.

.parent().parent() 等等是因为我有多行表来在gridview中显示我的数据,我需要遍历树然后找到我正在寻找和更改的文本框或标签具有更改数据的行的背景颜色。我不精通使用 jQuery 查找项目,因此 parent.parent... 事情。

回答by mpaf

With regards to the most voted answer, I think there is a much simpler syntax by just appending the extra request value into the source url.

关于投票最多的答案,我认为只需将额外的请求值附加到源 url 中就可以得到更简单的语法。

This:

这个:

$("#city_id").autocomplete({
    source: src+"?country_id="+$("#country_id").val().
    min_length: 3,
    delay: 300
});

does the same as:

与以下相同:

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

given that src is an url string.

鉴于 src 是一个 url 字符串。

回答by paperclip

While less than ideal, I've hacked/modified the plugin to get it to work for me.

虽然不太理想,但我已经破解/修改了插件以使其对我有用。

Simply, I've altered the AJAX jQuery function within the plugin.

简单地说,我改变了插件中的 AJAX jQuery 函数。

Around line 363 you'll see:

在第 363 行附近,您将看到:

        $.ajax({
            // try to leverage ajaxQueue plugin to abort previous requests
            mode: "abort",
            // limit abortion to this input
            port: "autocomplete" + input.name,
            dataType: options.dataType,
            url: options.url,
            data: $.extend({
                q: lastWord(term),
                search_type: $(input).attr('name'), // my mod to pickup multiple fields
                limit: options.max
            }, extraParams),
            success: function(data) {
                var parsed = options.parse && options.parse(data) || parse(data);
                cache.add(term, parsed);
                success(term, parsed);
            }
        });

I'm still looking for an elegant solution to this so feel free to keep suggestions coming.

我仍在寻找一个优雅的解决方案,所以请随时提出建议。

回答by Krunal

I am not sure why it is not working.

我不确定为什么它不起作用。

But you can first check/debug for value of $(this).attr('name').

但是您可以先检查/调试 的值$(this).attr('name')

Also one more thing as here explained[in options tab], you can check with Firebugto see ajax post request(for url and it's data) which will help you to resolve the problem.

还有一件事在这里解释[在选项选项卡中],您可以检查Firebug以查看 ajax 发布请求(对于 url 及其数据),这将帮助您解决问题。

回答by user3189971

Try with

试试

$( "#ricerca" ).autocomplete({
                source: "response.php?param=param",
                minLength: 2
});