JQuery Knockout - 分配json数据以选择选项

时间:2014-07-25 16:23:16

标签: javascript jquery json knockout.js

我有一个简单的选择下拉列表,我想从json数据中填充。当我将json数据硬编码为嵌入式javascript时,它可以工作,但是当我尝试使用JQuery的getJSON回调来检索数据时,它不会填充select。我已检查过网址是否有效并返回正确的json结果,我相信我并没有按照正确的顺序或其他方式调用它。

我尝试过搜索,很多人提供了我尝试过的例子,例如将json结果分配给全局变量。

下面的HTML:

<select data-bind="options: options, optionsText: 'name', optionsValue: 'name'"></select>

JS(与嵌入式jsondata一起使用)如下:

var jsdata = [{"id":1,"name":"Fruits","products":[{"id":1,"name":"Banana","price":0.99,"catid":1},{"id":2,"name":"Apple","price":0.49,"catid":1},{"id":3,"name":"Orange","price":0.69,"catid":1}]},{"id":2,"name":"Beverage","products":[{"id":4,"name":"Coca Cola","price":1.99,"catid":2},{"id":5,"name":"Dr. Pepper","price":1.89,"catid":2},{"id":6,"name":"Sprite","price":1.79,"catid":2},{"id":7,"name":"Mountain Dew","price":1.69,"catid":2},{"id":8,"name":"7-Up","price":1.59,"catid":2}]},
              {"id":3,"name":"test","products":[]}];

var ViewModel = function (js) {
        var self = this;
        self.json = js;
        self.options = ko.toJS(js);      
}    
var vm = new ViewModel(jsdata);
ko.applyBindings(vm);

jsfiddler是@ http://jsfiddle.net/psteele/7vcqX/#

尝试使用getJSON,但没有工作:

$.getJSON("url-to-data", null, function(data) {       
   var ViewModel = function (js) {
        var self = this;
        self.json = js;
        self.options = ko.toJS(js);      
   }    
   var vm = new ViewModel(data);
   ko.applyBindings(vm);
});

也尝试过:

var globaljson;
$.getJSON("url-to-data", null, function(data) {       
   globaljson = data;
});

var ViewModel = function (js) {
        var self = this;
        self.json = js;
        self.options = ko.toJS(js);      
   }    
   var vm = new ViewModel(globaljson);
   ko.applyBindings(vm);

2 个答案:

答案 0 :(得分:0)

根据Knockout documentation,您应该使用数组作为select的选项。所以尝试类似的事情:

jQuery.getJSON(url, function(data) {       
   var ViewModel = function (options) {
        var self = this;
        self.options = ko.observableArray($.map(options, function(key, value) { return { name: value, value: key } }));
   }    
   var vm = new ViewModel(data);
   ko.applyBindings(vm);
});

答案 1 :(得分:0)

你应该使用一些不同的代码来创建你的可观察数组:

$.getJSON('your url', function(data) {
    var ViewModel = function(js) {
        var self = this;
        self.json = js;
        self.options = ko.observableArray($.map(js, function(item) { return { name: item.name, value: item.id } }));
    };
    var vm = new ViewModel(data);
    ko.applyBindings(vm);
});

Demo.