jQuery HTML到JSON [英] jQuery HTML to JSON

查看:70
本文介绍了jQuery HTML到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

这怎么样?



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



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

 

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< div id =输入contenteditable =truestyle =border:1px solid; width:300px; < / div>< div style =clear:both:100px;>< b>编辑我!< / b>您可以使用CTRL + B更改粗体,ctrl + I更改斜体。 ;>< input type =buttonvalue =Get HTML>< / div>< div id =outputstyle =border:1px solid; clear:both; width:300px; height :100px; font-family:courier; font-size:10px;>< / div>  



btw为简单起见,我使用了 JSON.stringify ,但在生产环境中,您可能应该使用像jquery-json这样的库,旧的浏览器不支持,仍然在偷偷摸摸。


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 data JSON but I'm wondering how I can get the values as they are in the current DOM?

解决方案

How about this?

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

Pull out the HTML of your area, then convert it back to 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.stringify for 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.

这篇关于jQuery HTML到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆