【问题标题】:JQuery autocomplete error : Cannot read property 'label' of undefinedJQuery 自动完成错误:无法读取未定义的属性“标签”
【发布时间】:2019-08-01 18:06:07
【问题描述】:

参考AutoComplete in Bot Framework,实现了搜索URL的GET方法。

下面是我的代码:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="https://cdn.botframework.com/botframework- 
 webchat/latest/botchat.css" rel="stylesheet" />
<link rel="stylesheet" 
  href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet" 
 href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.botframework.com/botframework- 
webchat/latest/botchat.js"></script>
<style>
    .wc-chatview-panel {
        width: 350px;
        height: 500px;
        position: relative;
    }
</style>
 </head>
 <body>
   <div id="mybot"></div>
  </body>
 </html>
 <script src="https://cdn.botframework.com/botframework- 
  webchat/latest/CognitiveServices.js"></script>
  <script type="text/javascript">
 var searchServiceName = "abc";
 var searchServiceApiKey = "xyzabc";
 var indexName = "index1";
 var apiVersion = "2017-11-11";
var corsanywhere = "https://cors-anywhere.herokuapp.com/";

var suggestUri = "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs/suggest?api-version=" + apiVersion + "&search=how";
var autocompleteUri = "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs/autocomplete?api-version=" + apiVersion;
var searchUri = corsanywhere + "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs?api-version=" + apiVersion;


BotChat.App({
    directLine: {
        secret: "DIRECTLINEKEY"
    },
    user: {
        id: 'You'
    },
    bot: {
        id: '{BOTID}'
    },
    resize: 'detect'
}, document.getElementById("mybot"));

  </script>
   <script type="text/javascript">
        $(function () {
        $("input.wc-shellinput").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "GET",
                url: searchUri,
                dataType: "json",
                headers: {
                    "api-key": searchServiceApiKey,
                    "Content-Type": "application/json",

                    "Access-Control-Allow-Origin": "SAMPLEURL",
                    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE"
                },
                data: JSON.stringify({
                    top: 5,
                    fuzzy: false,
                    // suggesterName: "", //Suggester Name according to azure search index.
                    search: request.term
                }),
                success: function (data) {
                    if (data.value && data.value.length > 0) {


                        //RESPONSE FORMATTED as per requirements to hold questions based on input value(Below code is only for my reference i added)
                        var result = "";
                        var inputValue = request.term;
                        for (i = 0; i < data.value.length; i++) {
                            var allquestions = data.value[i].questions;

                            if (allquestions.length > 0) {
                                for (j = 0; j < allquestions.length; j++)
                                    if (allquestions[j].toLowerCase().indexOf(inputValue.toLowerCase()) != -1) {
                                        result = result + "," + allquestions[j];
                                    }
                            }
                        }
                        if (result != null) {
                            alert(result);

                            response(data.value.map(x => x["@search.text"])); ---Caught Error at this STEP
                        }
                        else { alert("no data"); }



                    }
                    else {
                        alert("No response for specific search term");
                    }
                }
            });
        },
        minLength: 3,
        position: {
            my: "left top",
            at: "left bottom",
            collision: "fit flip"
        },
        select: function (Event, ui) {

            $(document).ready(function () {

                var input = document.getElementsByClassName("wc-shellinput")[0];
                var lastValue = input.value;
                input.value = ui.item.value;
                var event = new CustomEvent('input', {
                    bubbles: true
                });
                // hack React15
                event.simulated = true;
                // hack React16
                var tracker = input._valueTracker;
                if (tracker) {
                    tracker.setValue(lastValue);
                }

                input.dispatchEvent(event);
            })

            $('wc-textbox').val("");
            Event.preventDefault();

            $(".wc-send:first").click();
        }

    });
});


</script>

我的示例 API 输出:

    { "@odata.context": "URL", "value": [{ "questions": [ "where are you", "where have you been", ] }, { "questions": [ "How are you?" ] } ] } 

我已成功获得 API 响应(data.value),但在

处出现异常
 response(data.value.map(x => x["@search.text"]));

错误信息:Uncaught TypeError: Cannot read property 'label' of undefined

我曾尝试将 @search.text 替换为 "value""@data.context" 但仍然出现错误。我想根据用户输入显示所有问题数据

【问题讨论】:

    标签: javascript c# jquery autocomplete botframework


    【解决方案1】:

    我终于能够通过以下解决方案解决我的问题。

    注意: JQuery Autocomplete "response" 方法将数组作为数据类型。

    解决方案: 1) 当我们将整个 API 数组结果传递给“response”方法时,结果必须有“label”关键字和正确的数据。

    传递整个 API 结果时的示例代码:

       response(data.value.map(x => x["@search.text"]));
    

    2) 当我们在 API 响应中没有“label”关键字时,我们必须根据要求格式化响应并创建一个我们想要显示为自动建议的新数据数组并传递给“response”方法。

    下面是相同的代码:

        var autoSuggestDataToDisplay= [];
                            var inputValue = request.term;
                            for (i = 0; i < data.value.length; i++) {
                                var allquestions = data.value[i].questions;
    
                                if (allquestions.length > 0) {
                                    for (j = 0; j < allquestions.length; j++)
                                        if (allquestions[j].toLowerCase().indexOf(inputValue.toLowerCase()) != -1) {
                                            result = result + "," + allquestions[j];
                                            if (autoSuggestDataToDisplay.indexOf(allquestions[j].toLowerCase()) === -1) {
                                                autoSuggestDataToDisplay.push(allquestions[j].toLowerCase());
                                            }
                                        }
                                }
                            }
                            if (result != null) { response(autoSuggestDataToDisplay); }
                            else { alert("no data"); }
    

    由于我在 API 响应中没有“标签”,所以我按照 #2 的方法解决了它。

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      相关资源
      最近更新 更多