简体   繁体   English

将JSON对象绑定到HTML元素

[英]Bind JSON object to HTML element

I want to bind a JSON object to a HTML element. 我想将JSON对象绑定到HTML元素。

eg 例如

I have a object "person" with the attributes "firstName", "lastName" 我有一个对象“person”,其属性为“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. 因此,如果HTML元素的值发生更改,那么对象人员也会更新。

is this possible in any way? 这有可能吗?

i use: 我用:

  • jquery jQuery的
  • ASP.NET MVC 3 ASP.NET MVC 3

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. 如果你将在你的应用程序中做很多这样的事情,你可能想要引入一个库,比如优秀的Knockout.js ,它使用MVVM来进行绑定。

Your markup would look something like this: 你的标记看起来像这样:

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

And in your JavaScript: 在你的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: 其他有用的链接:

First, add id attributes to your markup (you could do this with the DOM but for clarity's sake id s are probably best suited for this example): 首先,将id属性添加到标记中(您可以使用DOM执行此操作,但为了清楚起见, id可能最适合此示例):

<div class="person-list-item">
   <div id="firstname">John</div>
   <div id="lastname">Smith</div>
</div>

Use a jQuery event handler to update the fields whenever they are modified (this is an inefficient solution but gets the job done- worry about optimizing once you have something functional): 使用jQuery事件处理程序在修改字段时更新字段(这是一个效率低下的解决方案但是完成工作 - 一旦你有功能就担心优化):

// declare your object
function person(firstn, lastn) {
    this.firstname = firstn;
    this.lastname = lastn;
}

var myGuy = new person("John", "Smith");

$(document).ready(function () {
    $("#firstname").change(function () {
        myGuy.firstname = $("#firstname").val();
    });

    $("#lastname").change(function () {
        myGuy.lastname = $("#lastname").val();
    });

    // etc...
});

Now every time the fields are updated your object will be too. 现在,每次更新字段时,您的对象也将如此。

Simple one-way approach using jquery... 使用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" />

You can parse the JSON to turn it into a JavaScript object: 您可以解析JSON以将其转换为JavaScript对象:

var data = $.parseJSON(json_string);
// or without jQuery:
var data = JSON.parse(json_string);

If I understood your question correctly, you should have JSON that look like this: 如果我正确理解你的问题,你应该有这样的JSON:

[
    {
        "firstName": "John",
        "lastName": "Smith"
    },
    {
        "firstName": "Another",
        "lastName": "Person"
    } // etc
]

So you can just loop through the people like so: 所以你可以像这样循环遍历这些人:

$(document).ready(function() {
    var str = '[{"firstName":"John","lastName":"Smith"},{"firstName":"Another","lastName": "Person"}]',
        data = $.parseJSON(str);
    $.each(data, function() {
        var html = '<div class="person-list-item"><div>' + this.firstName + '</div><div>' + this.lastName + '</div></div>';
        $('#person-list').append(html);
     });
});​

Fiddle: http://jsfiddle.net/RgdhX/2/ 小提琴: http//jsfiddle.net/RgdhX/2/

I recommend taking a look at Knockout . 我建议看看Knockout Setting up data binding like you are looking for is very straightforward with it. 像你正在寻找的那样设置数据绑定非常简单。

您可以使用其中一个MVC / MVVM版本,例如Backbone.jsKnockoutjs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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