Tom Rudge Tom Rudge - 6 months ago 35
jQuery Question

Display raw api data with knockout

This should be fairly simple and although I'm new to ko I just don't seem to be able to get a result.

I want to add a function to my view model to call and display an API that simply has html text in it like:

<p class="class">This is my text</p>

The view/page should call the text using ko and display something like this:

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

I've been using $.getJSON requests inside a function. Really need the simplest way to do this. Thanks Stackers.


You mean an AJAX call that loads some text?

You need to set up your View Model, then apply some bindings, and at last set the result of the ajax call.

Remember to set the bind to data-bind='html:

document.viewModel = { MyText: ko.observable() };

ko.applyBindingsToDescendants(document.viewModel, document.getElementById("content"));

//make your ajax call and handle the result
//$.getJSON('/some/url', function(data){`
    document.viewModel.MyText('<p class="class">This is my text</p>');
<script src=""></script>
<div id="content">
  <span data-bind="html: MyText"></span>