jQuery UI Autocomplete JSON给出错误:Uncaught TypeError:无法使用'in'运算符来搜索'62'

ESD*_*tor 8 ajax jquery json jquery-ui autocomplete

我在使用自动填充功能在我的页面上工作时遇到了很多麻烦.当我在搜索输入中输入2个字符("OW")时,我得到预加载器图像(见下文),但它永远不会消失,我从未得到自动完成弹出窗口.在Chrome中查看控制台显示:

Uncaught TypeError: Cannot use 'in' operator to search for '62' in [{"value":103,"label":"FLOWER"},{"value":105,"label":"YELLOW"}] 
Run Code Online (Sandbox Code Playgroud)

以下是要返回的实际字符串(通过在成功块中添加警报(数据)来确认):

[{"kwrdID":103,"kwrdKeyWord":"FLOWER"},{"kwrdID":105,"kwrdKeyWord":"YELLOW"}]
Run Code Online (Sandbox Code Playgroud)

这是自动完成的主要代码

$("#searchInput").autocomplete({
source: function (request, response) {
    $.ajax({
        url: '@Url.Action("GetKeywords", "Home")',
        dataType: "json",
        data: {
            SearchTerm: request.term
        },
        success: function (data) {
            response($.map(data.keywords, function (item) {
                return {
                    label: item.kwrdKeyWord,
                    value: item.kwrdID
                }
            }));
        }
    });
},
    minLength: 2
});
Run Code Online (Sandbox Code Playgroud)

最后,这是预加载器(以防它是相关的).

$(document).ajaxStart(function () {
    var position = $('#divParent').position();
    position.left += (($('#divParent').width() / 2) - ($('#preloader').width() / 2));
    position.top += (($('#divParent').height() / 2) - ($('#preloader').height() / 2));
    $('#preloader').css(position).show();
    $('#preloader').show();
}).ajaxStop(function () {
    $('#preloader').hide();
});
Run Code Online (Sandbox Code Playgroud)

谁能帮忙解释一下这里发生了什么?

ESD*_*tor 14

这是一条很长的路,但经过几个小时的实验,我想出了这段代码:

$("#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
});
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常.事实是我的关键字是独一无二的,所以无论如何我都可以没有身份证.

  • 我认为修复它的是`JSON.parse`调用. (9认同)

Ner*_*rta 9

一点点有用的帮助:

如果你正在使用json,那么可能是"json对象"没有被解析,或者你已经用其他东西覆盖了变量(就像我最近愚蠢地做的那样).

对于第一个问题,请确保您的服务器知道"application/json"MIME类型,否则使用header(对于PHP)

我的意思是,在PHP中,首先使用它:

header("Content-type: application/json");
Run Code Online (Sandbox Code Playgroud)