JQuery自动完成与JSON结果不起作用

时间:2015-12-07 17:59:39

标签: javascript jquery jquery-ui autocomplete

我正在使用JQuery自动完成功能来显示可用课程列表。我正在做一个帖子来从服务器获取课程列表,我操纵数据以预期的格式,并将其传递给自动完成功能。问题是它不起作用,除非我硬复制并粘贴值newSource并将它们粘贴到源代码中。 变量newSource = [" Enc1001"," ENC1002"," Enc1003"," ENC1101" ....等]。 从服务器获取数据的ajax帖子

//Auto complete for search box
$('#AdditionalSearch').on('input', function () {
    var source = [];
    var inputValue = $('#AdditionalSearch').val();
    if (inputValue !== '') { //the value is not empty, we'll do a post to get the data.
        url = "/Course/CourseSearch";
        $.ajax({
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            cache: false,
            data: JSON.stringify({ "searchCourseValue": inputValue }),
            url: url,
            success: function (data) {
                if (data.Ok) {
                    var myData = JSON.parse(data.data);
                    var newSource = '[';
                    $.each(myData.ResultValue, function (index, item) {

                        if ((myData.ResultValue.length -1) == index)
                            newSource += '"' + item.Name+'"';
                        else
                            newSource += '"'+ item.Name + '",';
                    });
                    newSource += "]";
                    console.log(newSource);
                    source = newSource;
                }
                setNameAutoComplete(source);
            },
            error: function (jqXHR) {
                console.log(error);
            }
        });

    } else { //The user either delete all the input or there is nothing in the search box. 
            //The value is empty, so clear the listbox.
        setNameAutoComplete(source);
    }
});

//将来源传递给自动完成功能

var setNameAutoComplete = function (data) {
    console.log(data);
    $('#AdditionalSearch').autocomplete({
        source: data
    });
}

我在这里缺少什么东西吗?

1 个答案:

答案 0 :(得分:1)

当您在代码中粘贴newSource = ["Enc1001","ENC1002","Enc1003","ENC1101"....etc]时,您正在构建一个数组对象。但是,在success方法中,您正在构建一个字符串(该对象的字符串表示形式)。你想要做的是建立一个实际的数组。

        ...
        success: function (data) {
            if (data.Ok) {
                var myData = JSON.parse(data.data);
                var newSource = [];
                $.each(myData.ResultValue, function (index, item) {
                        newSource.push(item.Name);
                });
                console.log(newSource);
                source = newSource;
            }
            setNameAutoComplete(source);
        },
        ...