3

I'm using knockout js for data binding in my single page web application, I need to populate a dropdown list using a json object returned as response by an ajax call to the sever. I'm adding my model and ajax call here. Please suggest solutions.

var permissionRequestModel = {
fromDate: ko.observable(''),
toDate: ko.observable(''),
fulldayPermission: ko.observable(false),

fromTimeHH: ko.observable(''),
fromTimeMM: ko.observable(''),
toTimeHH: ko.observable(''),
toTimeMM: ko.observable(''),

permissionTypeOne: ko.observable(''),
permissionTypeTwo: ko.observable(''),

approverList: ko.observableArray([]),

reasonLeave: ko.observable('')

};

//ajax call

$(function () {

$.ajax({
    url: "{generic uri}",
    type: "GET",
    contentType: "application/json",
    dataType: "json",
    error: function () {
        alert("failed");
    },
    success: function (data) {
             alert("Success");
    }
});
});

I need to populate the ApproverList (ko.observablearray) with the json response.

1 Answer 1

3

Using the Knockout Mapping plugin:

approverList = ko.mapping.fromJS(data);

Or if you want to update an already populated view model:

success: function (data)
{
    ko.mapping.fromJS(data, approverList);
}
Sign up to request clarification or add additional context in comments.

2 Comments

can you show me where to write this line of code? inside the ajax success function?
Hi, it seems like your answer is right, but I was not able to make it work. Instead I was able to do it with "permissionRequestModel.approverList(data);" in the success function. Thanks for your answer and time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.