jQuery jQueryUI 自动完成 - 当没有返回结果时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2844103/
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:23:15  来源:igfitidea点击:

jQueryUI autocomplete - when no results are returned

jqueryjquery-uiautocomplete

提问by Brian M. Hunt

I'm wondering how one can catch and add a custom handler when empty results are returned from the server when using jQueryUI autocomplete.

我想知道当使用jQueryUI autocomplete从服务器返回空结果时,如何捕获并添加自定义处理程序。

There seem to be a few questions on this point related to the various jQuery plugins (e.g. jQuery autocomplete display “No data” error message when results empty), but I am wondering if there's a better/simpler way to achieve the same with the jQueryUI autocomplete.

在这一点上似乎有一些与各种 jQuery 插件相关的问题(例如,当结果为空时,jQuery 自动完成显示“无数据”错误消息),但我想知道是否有更好/更简单的方法来实现相同的 jQueryUI自动完成。

It seems to me this is a common use case, and I thought perhaps that jQueryUI had improved on the jQuery autocomplete by adding the ability to cleanly handle this situation. However I've not been able to find documentation of such functionality, and before I hack away at it I'd like to throw out some feelers in case others have seen this before.

在我看来,这是一个常见的用例,我认为 jQueryUI 可能通过添加干净处理这种情况的能力对 jQuery 自动完成进行了改进。但是,我一直无法找到此类功能的文档,在我对其进行破解之前,我想抛出一些触角,以防其他人以前看到过。

While probably not particularly influential, I can have the server return anything - e.g. HTTP 204: No Contentto a 200/JSON empty list - whatever makes it easiest to catch the result in jQueryUI's autocomplete.

虽然可能不是特别有影响力,但我可以让服务器返回任何内容 - 例如HTTP 204: No Content到 200/JSON 空列表 - 任何最容易在 jQueryUI 的自动完成中捕获结果的内容。

My first thought is to pass a callback with two arguments, namely a request object and a response callbackto handle the code, per the documentation:

我的第一个想法是response callback根据文档传递带有两个参数的回调,即一个请求对象和一个处理代码的回调:

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".

A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties).

第三个变体回调提供了最大的灵活性,可用于将任何数据源连接到自动完成。回调有两个参数:

一个请求对象,有一个名为“term”的属性,它指的是当前文本输入中的值。例如,当用户在城市字段中输入“new yo”时,自动完成术语将等于“new yo”。

一个响应回调,它需要一个参数来包含向用户建议的数据。此数据应根据提供的术语进行过滤,并且可以采用上述用于简单本地数据的任何格式(带有标签/值/两个属性的字符串数组或对象数组)。

When the response callback receives no data, it inserts returns a special one-line object-array that has a label and an indicator that there's no data (so the select/focus recognize it as the indicator that no-data was returned).

当响应回调没有接收到数据时,它会插入一个特殊的单行对象数组,它有一个标签和一个没有数据的指示符(因此选择/焦点将其识别为没有数据返回的指示符)。

This seems overcomplicated. I'd prefer to be able to use a source: "http://...", and just have a callback somewhere indicating that no data was returned.

这似乎过于复杂了。我希望能够使用源:“http://...”,并且只在某处有一个回调,表明没有返回数据。

Thank you for reading.

感谢您的阅读。

Brian

布赖恩

EDIT:

编辑:

Here's a wrapper function I created to solve this, based on @ThiefMaster's reassurance that it is the right way to go about it:

这是我创建的一个包装函数来解决这个问题,基于@ThiefMaster 的保证,这是解决这个问题的正确方法:

    function autocomplete(input, source_url, on_select, on_focus, default_data) {
        /* Autocompletion for an input field
         * input: the field for autocompleting
         * source_url: the JSON url for getting data
         * on_select: function (event,ui) - when someone selects an element
         * on_focus: function (event, ui) - when someone focuses an element
         * default_data: function () returning default data; alternatively is the
         *               default dataset e.g. {'label':'X','value':'Y'}
         */

        $(input).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: source_url,
                    dataType: "json",
                    data: request,
                    success: function (data) {
                        if (!data.length) { // expect [] or ""
                            var def_data = typeof(default_data) == 'function' ?
                                default_data() : default_data;
                            response(def_data);
                        } else {
                            response(data);
                        }
                    }
                });
            },
            minLength: 3,
            select: on_select,
            focus: on_focus,
        });
    }

采纳答案by ThiefMaster

Overwriting the responsefunction of the autocompleter object might work, but that's monkeypatching. Using the response callback is most likely the cleanest way to achieve what you want.

覆盖responseautocompleter 对象的功能可能会起作用,但那是monkeypatching。使用响应回调很可能是实现您想要的最干净的方式。

回答by Reza Mamun

It is easy to handle with responseoption

使用response选项很容易处理

$( 'input.Srch' ).autocomplete({
    minLength: 3,
    .......
    response: function(event, ui) {
        if (!ui.content.length) {
                var noResult = { value:"",label:"No results found" };
                ui.content.push(noResult);
        }
    }
});

Here is my screenshot:

这是我的截图:

enter image description here

在此处输入图片说明

回答by Vivan Menezes

Considering source as php script:

将源视为 php 脚本:

what i did in my code is I returned NO results message from php script like

我在代码中所做的是我从 php 脚本中没有返回结果消息,例如

$ArrayMe =  Array();
if(rows found){
  array_push( $ArrayMe ,array('key1'=> $val1, 'key2'=> $val2, 'key3'=> $val3));
} else {
 array_push( $ArrayMe ,array("message"=>"No results found" ));
}
echo json_encode($ArrayMe);

from jquery:

来自jQuery:

 $( "input#val1" ).autocomplete({
        minLength: 2,

        source:function (request, response) {
        $.ajax({
                type: 'get',
                url: "path/to/phpscript.php",
                dataType: "json",
                data: { term: request.term },
                success: function(data) {
                        response($.map(data, function (value) {
                            if(value.message){
                                console.log(value.message);
                                $('p#val2').html("");
                                $('p#val3').html("");
                                return {Message: value.message}
                           } else {
                                return {
                                    key1: value.val1,
                                    key2: value.val2,
                                    key3: value.val3

                                }
                           }
                        }));
                    }   
                });
   },  
        focus: function( event, ui ) {
            $( "input#val1" ).val( ui.item.val1);
            $( "p#val2" ).html( ui.item.val2);
            $( "p#val2" ).html( ui.item.val3);
            return false;
        },
        select: function( event, ui ) {
            $( "input#val1" ).val( ui.item.val1);

            $( "p#val2" ).html( ui.item.val2);
            $( "p#val3" ).html( ui.item.val3);


            return false;
        }
    }).autocomplete( "instance" )._renderItem = function( ul, item ) {
        if(item.Message){
            return $( "<li>" )
                .append( "<div>" + item.Message +"</div>" )
                .appendTo( ul );
        } else{
            return $( "<li>" )
                .append( "<div>" + item.val1+ " | " + item.val2+  " | " + item.val3+"</div>" )
                .appendTo( ul );
        }
    };

. It worked perfectly fine for me.

. 它对我来说非常好。

If no data gets message as well as triggers required fields.

如果没有数据获取消息以及触发必填字段。

I am very poor in explanation so i posted entire code to make it easier.

我的解释很差,所以我发布了整个代码以使其更容易。