jQuery自动完成错误:无法读取未定义的属性“标签" [英] JQuery autocomplete error : Cannot read property 'label' of undefined

查看:161
本文介绍了jQuery自动完成错误:无法读取未定义的属性“标签"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考 Bot Framework中的自动完成,我已经实现了搜索URL的GET方法.

With reference to AutoComplete in Bot Framework , I had implemented GET method of search URL.

下面是我的代码:

<!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),但是在

I am getting API response successfully (data.value) but got exception at

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

错误消息:未捕获的TypeError:无法读取未定义的属性'label'

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

I had tried replacing @search.text with "value" and "@data.context" but still am getting error. I want to display all questions data based on user input

推荐答案

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

I am finally able to fix my issue with below solution.

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

Note: JQuery Autocomplete "response" method takes array as data type.

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

Solution: 1) when we are passing entire API array results to "response" method, results must have "label" keyword with proper data.

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

sample code while passing entire API results:

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

2)当API响应中没有"label"关键字时,我们必须根据需求设置响应格式,并创建一个新的数据数组,以自动提示的方式显示并传递给"response"方法.

2) when we don't have "label" keyword in API response, we have to format response as per requirements and create a new array of data that we want to display as auto suggest and pass to "response" method.

下面是相同的代码:

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

As i dont have "label" in API response, I followed #2 approach and solved it.

这篇关于jQuery自动完成错误:无法读取未定义的属性“标签"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆