jQuery UI Autocomplete JSON gives error: Uncaught TypeError: Cannot use 'in' operator to search for '62' in

后端 未结 4 1336
梦如初夏
梦如初夏 2020-12-17 21:07

I am having a great deal of trouble getting autocomplete to work on my page. When I enter 2 characters (\"OW\") into my search input, I get the preloader image (see below),

相关标签:
4条回答
  • 2020-12-17 21:27

    instead of writing replace data.keywords with JSON.parse(data) at this line : response($.map(data.keywords, function (item) {.

    BR, Hazem

    0 讨论(0)
  • 2020-12-17 21:40

    a little help that can be useful:

    if you're using json, it might be that the "json object" isn't parsed, or you've overwritten the variable with others tings (like what I did stupidly recently).

    for the first problem, be sure that your server know "application/json" MIME type, else use header (for PHP)

    I mean, in PHP, use this before all:

    header("Content-type: application/json");
    
    0 讨论(0)
  • 2020-12-17 21:43

    here how you use the function for the source property

    source:function(request,response) {
        var url = "your url";
        var postdata = "your data"; // normally you might use request.term to get the current user input
        $.ajax({url:url,data:postdata,success:function(responsedata){
            response($.parseJSON(responsedata))
        }});
    }
    

    The response function accepts array of JSON objects

    0 讨论(0)
  • 2020-12-17 21:46

    It was a long road, but after many hours of experimenting I came up with this code:

    $("#searchInput").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("GetKeywords", "Home")',
                dataType: "json",
                data: {
                    SearchTerm: request.term
                },
                success: function (data) {
                    var parsed = JSON.parse(data);
                    var newArray = new Array(parsed.length);
                    var i = 0;
    
                    parsed.forEach(function (entry) {
                        var newObject = {
                            label: entry.kwrdKeyWord
                        };
                        newArray[i] = newObject;
                        i++;
                    });
    
                    response(newArray);
                },
                error: function (message) {
                    response([]);
                }
            });
        },
        minLength: 2
    });
    

    This appears to work fine. The truth is my keywords are unique, so I can live without the ID anyway.

    0 讨论(0)
提交回复
热议问题