Autocomplete.js建议?

时间:2013-05-29 20:36:57

标签: javascript jquery ajax autocomplete

我的文本框中有一个自动完成插件(DevBridge AutoComplete)。

$('#myTextBox').autocomplete({
    serviceUrl: '/Handler/Autocomplete.ashx?'
});

正在进行Ajax调用(我可以看到Fiddler中的JSON返回),我得到这样的回报:

[{"Key":39,"Value":"118"},{"Key":40,"Value":"155"},{"Key":2,"Value":"16"}]

但我一直收到错误:

Unable to get property 'length' of undefined or null reference

在这部分代码中:

verifySuggestionsFormat: function (suggestions) {
        // If suggestions is string array, convert them to supported format:
        if (suggestions.length && typeof suggestions[0] === 'string') {
            return $.map(suggestions, function (value) {
                return { value: value, data: null };
            });
        }

        return suggestions;
    }

我不确定这意味着什么。谁能告诉我如何解决这个问题?它只是语法吗?我不确定在哪里/如何添加这些建议...

1 个答案:

答案 0 :(得分:0)

suggestions为null或未定义。

在检查变量之前,请测试它是否存在:

if (!suggestions) return;

例如:

verifySuggestionsFormat: function (suggestions) {

    // Fail fast if suggestions is not valid
    if (!suggestions) return;

    // If suggestions is string array, convert them to supported format:
    if (suggestions.length && typeof suggestions[0] === 'string') {
        return $.map(suggestions, function (value) {
            return { value: value, data: null };
        });
    }

    return suggestions;
}