简体   繁体   中英

Knockout JS Mapping from JSON not working

I'm receiving a JSON string and attempting to map it to a KOJS VM, but I don't see why the below code isn't working.

Here's my JS file:

var viewModel = {};

$.ajax({
  url: '../data/settings',
  cache: false,
  success: function(data) {
    alert(data);
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
  }
});

The first alert displays:

{"remember":"false"}

My HTML, which isn't working is:

<span data-bind="value:remember"></span>

Do you know what might be going wrong here? Thanks!

It looks like your data might not be a JSON string so you want to use fromJS instead:

viewModel = ko.mapping.fromJS(data);

This question can help with debugging bindings: How to debug template binding errors for KnockoutJS?

I think the problem may be your binding code:

<span data-bind="value:remember"></span>

should be:

<span data-bind="text:remember"></span>

See this fiddle: http://jsfiddle.net/kboucher/Jj9DZ/

'value' is for form fields that have a value property (and may be abstracted to include select boxes as well)

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