28

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

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

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

我的 jQuery:

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

这是我的 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>

有什么建议么?

4

13 回答 13

47

我正在使用现在是 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
    });
});
于 2010-11-11T12:22:38.273 回答
4

试试这个:

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

另请参阅此处

于 2010-09-07T13:27:33.403 回答
2

您可以像这样使用内置的 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(){});
                }
         });
     });

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

于 2011-12-23T05:52:30.563 回答
2

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

我试过

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

谢谢

于 2012-01-09T06:34:09.860 回答
1

虽然不太理想,但我已经破解/修改了插件以使其为我工作。

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

在第 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);
            }
        });

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

于 2010-04-28T10:18:48.227 回答
1
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' );
    }
})

使用 jquery.ui.autocomplete 1.8.17 为我工作

于 2012-07-26T16:07:01.117 回答
1

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

使用 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");
            }
        });
    }

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

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

于 2013-03-15T21:41:50.260 回答
1

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

这:

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

与以下内容相同:

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

鉴于 src 是一个 url 字符串。

于 2013-03-27T12:42:34.487 回答
0

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

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

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

于 2010-04-28T09:07:40.877 回答
0

首先使用 .each ,然后您可以使用 $(this) 并将所需的任何内容设置为变量。结果变量可用于自动完成

$(".autosuggest").each(function (index, object) {
    var autosuggestType = $(this).attr("autoSuggestType");
    $(this).autocomplete("url",
            {                    
                extraParams: {
                    autoSuggestType: autosuggestType
                },
于 2011-05-17T12:57:43.163 回答
0

我有同样的问题,但奇怪的是,只有自动完成插件的缩小版本。当我使用非缩小版本时,它可以工作。我还没有看过缩小版,看看有什么不同。

于 2011-06-06T20:58:16.767 回答
0

尝试

$( "#ricerca" ).autocomplete({
                source: "response.php?param=param",
                minLength: 2
});
于 2014-01-13T11:14:01.660 回答
0

我知道它已经被回答了。但我希望这对将来的人有所帮助,并节省很多时间和痛苦。

(you can replace 'CRM.$' with '$' or 'jQuery' depending on your jQuery version)

完整代码如下:这是我为文本框所做的,以使其在 CiviCRM 中自动完成。希望它可以帮助某人

CRM.$( 'input[id^=custom_78]' ).autocomplete({
            autoFill: true,
            select: function (event, ui) {
                    var label = ui.item.label;
                    var value = ui.item.value;
                    // Update subject field to add book year and book product
                    var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                    //book_year_value.replace('Book Year ','');
                    var subject_value = book_year_value + '/' + ui.item.label;
                    CRM.$('#subject').val(subject_value);
                    CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                    CRM.$('input[id^=custom_78]').val(ui.item.label);
                    return false;
            },
            source: function(request, response) {
                CRM.$.ajax({
                    url: productUrl,
                        data: {
                                        'subCategory' : cj('select[id^=custom_77]').val(),
                                        's': request.term,
                                    },
                    beforeSend: function( xhr ) {
                        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },

                    success: function(result){
                                result = jQuery.parseJSON( result);
                                //console.log(result);
                                response(CRM.$.map(result, function (val,key) {
                                                         //console.log(key);
                                                         //console.log(val);
                                                         return {
                                                                 label: val,
                                                                 value: key
                                                         };
                                                 }));
                    }
                })
                .done(function( data ) {
                    if ( console && console.log ) {
                     // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                    }
                });
            }
  });

关于我如何在自动完成中将数据返回到这个 jquery ajax 调用的 PHP 代码:

/**
 * This class contains all product related functions that are called using AJAX (jQuery)
 */
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
  static function getProductList() {
        $name   = CRM_Utils_Array::value( 's', $_GET );
    $name   = CRM_Utils_Type::escape( $name, 'String' );
    $limit  = '10';

        $strSearch = "description LIKE '%$name%'";

        $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
    $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );

        if (!empty($subCategory))
        {
                $strSearch .= " AND sub_category = ".$subCategory;
        }

        $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
        $resultArray = array();
        $dao = CRM_Core_DAO::executeQuery( $query );
        while ( $dao->fetch( ) ) {
            $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
        }
        echo json_encode($resultArray);
    CRM_Utils_System::civiExit();
  }
}
于 2016-12-09T16:41:32.083 回答