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

发布于 2024-08-30 05:04:37 字数 1181 浏览 7 评论 0原文

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

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

除了查询之外,我想将输入名称属性发送到服务器,但我似乎无法在 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>

有什么建议吗?

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.

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.

My jQuery:

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

This is my 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

左岸枫 2024-09-06 05:04:37

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

$(document).ready(function() {
    src = 'http://example.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
    });
});

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.

$(document).ready(function() {
    src = 'http://example.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
    });
});
空城旧梦 2024-09-06 05:04:37

试试这个:

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

另请参阅此处

Try this:

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

See also here

來不及說愛妳 2024-09-06 05:04:37

您可以像这样使用内置的 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

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

          $(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

瘫痪情歌 2024-09-06 05:04:37

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

我尝试了

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

谢谢

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

Thanks

疯到世界奔溃 2024-09-06 05:04:37

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

简而言之,我更改了插件中的 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);
            }
        });

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

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.

Around line 363 you'll see:

        $.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.

源来凯始玺欢你 2024-09-06 05:04:37
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

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

真心难拥有 2024-09-06 05:04:37

使用 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... 的事情。

Using the autocomplete in 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.

    $(".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.

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.

故人的歌 2024-09-06 05:04:37

关于得票最多的答案,我认为只需将额外的请求值附加到源 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 字符串。

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.

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.

坏尐絯 2024-09-06 05:04:37

我不知道为什么它不起作用。

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

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

I am not sure why it is not working.

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

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

你爱我像她 2024-09-06 05:04:37

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

$(".autosuggest").each(function (index, object) {
    var autosuggestType = $(this).attr("autoSuggestType");
    $(this).autocomplete("url",
            {                    
                extraParams: {
                    autoSuggestType: autosuggestType
                },

use a .each first, then you can use $(this) and set whatever you need into a variable. the resulting variable can be used in the autocomplete

$(".autosuggest").each(function (index, object) {
    var autosuggestType = $(this).attr("autoSuggestType");
    $(this).autocomplete("url",
            {                    
                extraParams: {
                    autoSuggestType: autosuggestType
                },
风苍溪 2024-09-06 05:04:37

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

I had the same problem, but oddly enough, only with the minified version of the autocomplete plugin. When I used the non-minified version, it works. I haven't looked at the minified version yet to see what the difference might be.

云仙小弟 2024-09-06 05:04:37

尝试用

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

Try with

$( "#ricerca" ).autocomplete({
                source: "response.php?param=param",
                minLength: 2
});
世界如花海般美丽 2024-09-06 05:04:37

我知道它已经得到答复。但我希望这能帮助将来的人并节省大量时间和痛苦。

(您可以将“CRM.$”替换为“$”或“jQuery”,具体取决于您的 jQuery 版本)

完整代码如下:这是我为文本框所做的,使其在 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();
  }
}

I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.

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

complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone

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

PHP code on how I'm returning data to this jquery ajax call in autocomplete:

/**
 * 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();
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文