KnockoutJS映射,JSON从的WebAPI [英] KnockoutJS mappings, JSON from WebAPI

查看:259
本文介绍了KnockoutJS映射,JSON从的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够绑定JSON使用以下code从.NET的WebAPI返回到淘汰赛视图模型。

 功能视图模型(){
    VAR自我=这一点;
    self.temps = ko.observableArray([]);
}$(函数(){
    VAR模型=新视图模型();    $获得('../ API /温度/'功能(数据){
        model.temps(数据);
    });    ko.applyBindings(模型);});

当我尝试使用瑞恩·尼迈耶的映射例子我使用的时候变得空 ko.utils.parseJson 在我返回的JSON,当我尝试使用 ko.utils.arrayMap 直接我越来越不确定的。

我也挣扎,如果我尝试以下方法采取get请求到一个单独的功能,我的数据绑定工作停止

 函数dataFromServer(){
    $获得('../ API /温度/'功能(数据){
        返回的数据;
    });
}$(函数(){
    VAR模型=新视图模型();
    VAR数据= dataFromServer();
    model.temps(数据);    ko.applyBindings(模型);});

从服务器返回的JSON:

<$p$p><$c$c>[{\"Id\":1,\"Name\":\"Test1\",\"TypeId\":100,\"Temp\":21.0,\"Peak\":true},{\"Id\":2,\"Name\":\"Test2\",\"TypeId\":100,\"Temp\":21.0,\"Peak\":true},{\"Id\":3,\"Name\":\"Test3\",\"TypeId\":101,\"Temp\":21.0,\"Peak\":true}]


解决方案

您的AJAX调用是异步的,所以它不会从你这里函数立即返回您的数据:

  $。获得('../ API /温度/'功能(数据){
        返回的数据;
    });

您可能想传递你想要写的结果可观察/ observableArray来给你的函数,如:

 函数dataFromServer(临时工){
    $获得('../ API /温度/'功能(数据){
        返回临时工(数据);
    });
}

然后调用它像:

  VAR模型=新视图模型();
dataFromServer(model.temps);

I am able to bind JSON returned from .net WebAPI to a knockout viewmodel using the following code.

function viewModel() {
    var self = this;
    self.temps = ko.observableArray([]);
}

$(function () { 
    var model = new viewModel();

    $.get('../api/Temp/', function (data) { 
        model.temps(data);
    });

    ko.applyBindings(model);       

});

When I try to use Ryan Niemeyer 's mapping example I am getting null when using ko.utils.parseJson on my returned Json and when I try to use the ko.utils.arrayMap directly I am getting undefined.

I am also struggling to take the get request into a separate function if I try the following, my data binding stops working

function dataFromServer() {
    $.get('../api/Temp/', function (data) { 
        return data;
    });
}

$(function () { 
    var model = new viewModel();
    var data = dataFromServer();
    model.temps(data);

    ko.applyBindings(model);       

});

Returned JSON from server :

[{"Id":1,"Name":"Test1","TypeId":100,"Temp":21.0,"Peak":true},{"Id":2,"Name":"Test2","TypeId":100,"Temp":21.0,"Peak":true},{"Id":3,"Name":"Test3","TypeId":101,"Temp":21.0,"Peak":true}]

解决方案

Your AJAX call is asynchronous, so it will not return your data immediately from your function here:

$.get('../api/Temp/', function (data) { 
        return data;
    });

You might want to pass the observable/observableArray that you want to write the result to into your function like:

function dataFromServer(temps) {
    $.get('../api/Temp/', function (data) { 
        return temps(data);
    });
}

Then call it like:

var model = new viewModel();
dataFromServer(model.temps);

这篇关于KnockoutJS映射,JSON从的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆