[英]Converting Javascript object to Javascript array
我正在使用一個可剔除的可觀察數組來填充一個dropdownlist。如果我對數組值進行硬編碼,則會填充dropdownlist。但是我現在正嘗試從數據庫中獲取數據。我正在使用JSON格式的javascript對象。 javascript對象的單個屬性,即; 認證,我正在創建一個要傳遞回腳本的數組,但是每次傳遞回的值都是不確定的,而該數組會顯示在控制台中。
轉換為我正在使用的數組的代碼是
var getCertifications = function () {
$.ajax({
type : "GET",
async : false,
url : "/Provider/GetCertifications",
dataType : "json",
success: function (data) {
var arrCertification = [];
$.each(data, function (i, item) {
arrCertification.push((item.Certification));
});
return arrCertification;
},
error : function () {
alert(" An error occurred.");
}
});
};
淘汰賽可觀察到的代碼是
var certificates = getCertifications();
self.certificationArray = ko.observableArray(certificates);
HTML是
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Certification:</label>
<div class="col-sm-6">
<select class="form-control" id="certification" name="certification" data-bind="value: certification, options: certificationArray, optionsCaption: 'Select a Certification'">
</select>
</div>
</div>
有人可以指導我哪里出錯了。
getCertifications()函數不返回任何內容。 它所做的只是啟動一個ajax調用。
您需要使用某種回調或promise對象來獲取此調用的結果。 使用回調看起來像:
var getCertifications = function (cb) {
$.ajax({
type : "GET",
async : false,
url : "/Provider/GetCertifications",
dataType : "json",
success: function (data) {
var arrCertification = [];
$.each(data, function (i, item) {
arrCertification.push((item.Certification));
});
cb(arrCertification);
},
error : function () {
alert(" An error occurred.");
}
});
};
getCertifications(function(certificates) {
self.certificationArray = ko.observableArray(certificates);
});
更好的模式是使用諾言。 $ .ajax方法返回一個promise。 但是,為了了解異步代碼的處理方法,回調方法是一個不錯的起點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.