通过Ajax调用淘汰映射json

时间:2013-07-29 18:26:10

标签: knockout-mapping-plugin

我尝试直接在Ajax调用中映射和绑定JSON数据但没有成功。警报显示请求的数据。如果我将此警报的内容复制/粘贴到测试变量中,则映射可以正常工作。为什么我不能直接映射/绑定到结果? 'test'和'result.d'之间可能有什么区别? (绑定到结果 - 没有.d也不起作用。)

感谢您的帮助。

 var test = { "formulier": { "titel": "test", "formulier_id": 4, "vragen": [{ "vraag_id": 5, "vraag": "Hoe gaat het?", "soortvraag_id": 4, "soortwaarde_id": 13, "verplicht": false, "antwoorden": [] }, { "vraag_id": 6, "vraag": "Dit is een kopje", "soortvraag_id": 18, "soortwaarde_id": 13, "verplicht": false, "antwoorden": [] }, { "vraag_id": 3, "vraag": "vraag 3k", "soortvraag_id": 6, "soortwaarde_id": 13, "verplicht": false, "antwoorden": [{ "antwoord": "nieuw2", "antwoord_id": 7, "vraag_id": 3, "iscorrect": true }, { "antwoord": "echt waar?", "antwoord_id": 5, "vraag_id": 3, "iscorrect": false }, { "antwoord": "nieuw 123", "antwoord_id": 2, "vraag_id": 3, "iscorrect": false }, { "antwoord": "nieuw", "antwoord_id": 6, "vraag_id": 3, "iscorrect": false }] }] } }

            // This doesn't work 
            $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "../formulierService.asmx/getLeegFormulier",
                        data: "{'id': " + 4 + "}",
                        dataType: "json",
                        success: function (result) {
                            alert(result.d); //content of alert was pasted into var test above
                            var ViewModel = ko.mapping.fromJS(result.d); 
                            ko.applyBindings(ViewModel);
                        }
            });

            // This does work
            var ViewModel2 = ko.mapping.fromJS(test);
            ko.applyBindings(ViewModel2);

1 个答案:

答案 0 :(得分:1)

这里,要使用fromJS,您需要将json字符串反序列化为js对象。

var test = JSON.parse(result.d);

然后,打电话

var ViewModel2 = ko.mapping.fromJS(test);

另一种选择是直接使用fromJSON,而不是fromJS

var ViewModel2 = ko.mapping.fromJSON(result.d);