Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind JSON object to HTML element

I want to bind a JSON object to a HTML element.

e.g.

I have a object "person" with the attributes "firstName", "lastName"

<div class="person-list">
  <div class="person-list-item">
    <div>John</div>    ---> bind it to person.firstName
    <div>Smith</div>   ---> bind it to person.lastName
  </div>
</div>

so, if a value of the HTML elements gets changed, then will also the object person gets updated.

is this possible in any way?

i use:

  • jquery
  • ASP.NET MVC 3
like image 515
Wasser Trinker Avatar asked Mar 05 '12 17:03

Wasser Trinker


People also ask

How do you bind a JSON object in HTML?

data-bind="foreach: list" It is similar of using for-each loop in javascript. It will iterate over all the elements in list from DataModel (Json object). <img data-bind = "attr: {src: url}"/> Here we are binding src attribute of <img>tag with a property (named 'url' ) of a list node in DataModel (Json object).

How fetch data from JSON to HTML?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

Can JSON hold HTML?

As long as your data is formatted as one of these types, it should be valid. However, if your data contains HTML, there are certain things that you need to do to keep the browser happy when using your JSON data within Javascript. Escape the forward slash in HTML end tags. <div>Hello World!


2 Answers

If you'll be doing this a lot in your application, you may want to bring in a library such as the excellent Knockout.js which uses MVVM to do bindings as you describe.

Your markup would look something like this:

<div data-bind="text: firstName"></div>
<div data-bind="text: lastName"></div>

And in your JavaScript:

function MyViewModel() {
    this.firstName = "John";
    this.lastName = "Smith";
}

ko.applyBindings(new MyViewModel());

You can also use a data set if there are many "people." Try out this tutorial if you would like to learn how to do that: Working with Lists and Collections.

Other useful links:

  • Introduction tutorial
  • Excellent demo video (about 30 minutes)
like image 68
Drew Gaynor Avatar answered Sep 22 '22 07:09

Drew Gaynor


Simple one-way approach using jquery...

    var resp = your_json_data;
    $(function () {
        $(".jsondata").each(function () {
            $(this).html(eval($(this).attr("data")));
        });
    });

then in the page...

 <span class="jsondata" data="resp.result.formatted_phone_number" />
like image 35
Sean Avatar answered Sep 23 '22 07:09

Sean