简体   繁体   中英

JQuery autocomplete error : Cannot read property 'label' of undefined

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

Below is my code:

<!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>

My Sample API Output:

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

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

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

Error Message: Uncaught TypeError: Cannot read property 'label' of undefined

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.

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

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

sample code while passing entire API results:

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

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.

Below is code for same:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM