jQuery自动完成错误:无法读取未定义的属性“标签”

时间:2019-03-11 12:13:49

标签: javascript c# jquery autocomplete botframework

参考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"]));

错误消息:未捕获的类型错误:无法读取未定义的属性“标签”

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

1 个答案:

答案 0 :(得分:0)

我终于可以使用以下解决方案解决问题。

注意:jQuery自动完成“响应”方法将数组作为数据类型。

解决方案: 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的方法进行了解决。