Javascript jQuery HTML 到 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6918249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:45:32  来源:igfitidea点击:

jQuery HTML to JSON

javascriptjqueryhtmljson

提问by Fred

I'm using the jQuery template plugin to generate HTML from JSON data which the user than manipulates (and, potentially alters). I'm looking for a way to read this html back into JSON so I can save it back to my server. jQuery offers a $.tmplItem()method which returns the originally set dataJSON but I'm wondering how I can get the values as they are in the current DOM?

我正在使用 jQuery 模板插件从 JSON 数据生成 HTML,用户可以操作(并且可能会更改)。我正在寻找一种方法将这个 html 读回 JSON,以便我可以将它保存回我的服务器。jQuery 提供了一个$.tmplItem()方法,它返回最初设置的dataJSON,但我想知道如何获取当前 DOM 中的值?

回答by Jamie Treworgy

How about this?

这个怎么样?

http://jsfiddle.net/mWuHe/14/

http://jsfiddle.net/mWuHe/14/

Pull out the HTML of your area, then convert it back to JSON:

拉出您所在区域的 HTML,然后将其转换回 JSON:

$(':button').click(function() {
    $('#output').text(JSON.stringify({ 
        data:$('#input').html() 
    }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input" contenteditable="true" style="border: 1px solid;width:300px; height:100px;"><b>Edit me!</b> You can use CTRL+B to change bold, ctrl+I to change italics.</div>
<div style="clear:both;">
    <input type="button" value="Get HTML">
</div>
<div id="output" style="border: 1px solid;clear:both;width:300px;height:100px;font-family:courier;font-size:10px;">

</div>

btw I used JSON.stringifyfor simplicty, but in a production environment you should probably use a library like jquery-json, since some old browsers that don't support that are still skulking around.

顺便说一句,我使用JSON.stringify简单,但在生产环境中,您可能应该使用像 jquery-json 这样的库,因为一些不支持的旧浏览器仍在徘徊。

回答by Matt Ball

The nicest way to get this done will be some sort of data binding, such as the jQuery data link pluginor (perhaps a bit much for your current needs) Knockout.

完成此任务的最佳方法是某种数据绑定,例如jQuery 数据链接插件或(可能对您当前的需求有点多)Knockout