问题映射从ajax调用局部变量返回的对象以进行淘汰自动完成

时间:2017-03-03 23:36:02

标签: jquery knockout.js

我正在使用knockout(v3.2)自动完成功能,并且我有一个返回值列表的ajax调用。

var remoteData = $.ajax({
                url: '@Url.Action("GetAllSkills", "EmployeeSkills")',
                data: { },
                dataType: 'json',
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var array = ($.map(data, function (item) {
                        return {
                            id: item.SkillsId,
                            name: item.SkillName
                        };
                    }));      
                }
            });

返回的对象被分配给remoteData变量,该变量具有一个名为' responseText'的属性。具有以下数据 - > " [{" SkillId":1," SkillName":" Test Skill 1"},{" SkillId":2, " SkillName":"测试技能2"},{" SkillId":3,"技能名称":"测试技能3&# 34;},{" SkillId":4," SkillName":"测试技巧4"},{" SkillId":5,& #34; SkillName":"测试技巧5"},{" SkillId":6," SkillName":"测试技巧6&#34 ;},{" SkillId":7," SkillName":"测试技巧7"},{" SkillId":8,&# 34; SkillName":" abc"},{" SkillId":10," SkillName":" Test Skill 34"}, {" SkillId":11," SkillName":" XYZ"},{" SkillId":12," SkillName&#34 ;:"全新的技能!"},{" SkillId":13," SkillName":"又一种新技能"}, {" SkillId":1000," SkillName":" New Test Skill 1"},{" SkillId":1001," SkillName":" test1"},{" SkillId":1002," SkillName":" .NET v4.5"}, {" SkillId ":1003," SkillName":" C#"},{" SkillId":1004," SkillName":&#34 ; ASP.NET"},{" SkillId":1006," SkillName":" MVC"},{" SkillId&#34 ;: 1007" SkillName":" PHP"},{" SkillId":1008," SkillName":" F#" },{" SkillId":1009," SkillName":"角"},{" SkillId":1010," SkillName& #34;:"测试100"}]"

在我的视图模型中,我有以下代码......

function ActivityViewModel() {
    var self = this;
    self.skills = remoteData;
    self.selectedOption = ko.observable('');
    self.options = self.skills.map(function (element) {    
      return {
        label: element.SkillName,
        value: element.SkillsId,
        object: element
      };
    });

我收到以下错误 - > self.skills.map不是新ActivityViewModel的函数。

我不知道为什么会这样。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您将remoteData分配给ajax调用的结果。这与将其设置为ajax调用检索的值不同。 ajax函数返回一个promise对象,你必须添加一个回调来检索值。

jQuery Deferred and Promise walkthrough

尝试在成功回调中分配您的remoteData变量。这可能不起作用,具体取决于代码的其余部分的结构。如果你在ajax调用完成之前尝试使用remoteData变量并点击成功回调,它仍然会显示为未定义。

var remoteData;
$.ajax({
    url: '@Url.Action("GetAllSkills", "EmployeeSkills")',
    data: {},
    dataType: 'json',
    type: 'GET',
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        remoteData = ($.map(data, function (item) {
            return {
                id: item.SkillsId,
                name: item.SkillName
            };
        }));
    }
});