简体   繁体   中英

Converting Javascript object to Javascript array

I am using a knockout observable array to populate a dropdownlist.The dropdownlist gets populated if I hardcode the array values.But I am now trying to get the data from the database.I am using JSON format for the javascript object.I am accessing a single property of the javascript object ie; Certification and I am creating an array which I am passing back to a script.But each time the value that is passed back is undefined whereas the array shows up in the console.

The code to convert to an array that I am using is

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.");
        }
     });
 }; 

The code for the knockout observables is

  var certificates = getCertifications();
  self.certificationArray = ko.observableArray(certificates);

and the HTML is

 <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>

Could some one please guide me on where I am going wrong.

The getCertifications() function doesn't return anything. All it does is kick off an ajax call.

You need to use some sort of call back or promise object to get the results of this call. Using a callback this would look something like:

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);
 });

A better pattern would be to use promises. The $.ajax method returns a promise. However the callback approach is a good place to start in order to get an understanding of handling asynchronous code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM