使用jQuery将JSON附加到表单并提交 [英] Use jQuery to attach JSON to a form and submit it
本文介绍了使用jQuery将JSON附加到表单并提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< form action =/ commentsmethod =postid = comments_form>
<提交>发布< /提交>
< / form>
解决方案
假设您的JSON对象是 myData
变量(并且您制作 JSON.stringify
可用):
$('#comment_form')。submit(function(){
var $ hidden = $(< input type ='hidden'name ='myData'/>);
$ hidden.val(JSON.stringify(myData));
$(this).append($ hidden);
return true;
});
上面的代码实时创建一个隐藏表单输入,并为您的JSON的字符串表示赋予其值对象,然后在提交之前将其附加到表单中。
Given this empty form, how would I use jQuery to attach a JSON object as params and then submit it? The form should standard submit, not AJAX.
<form action="/comments" method="post" id="comments_form">
<submit>Post</submit>
</form>
解决方案
Assuming your JSON object is the myData
variable (and you make JSON.stringify
available):
$('#comment_form').submit(function() {
var $hidden = $("<input type='hidden' name='myData'/>");
$hidden.val(JSON.stringify(myData));
$(this).append($hidden);
return true;
});
The above code creates a hidden form input on the fly and gives its value the string representation of your JSON object, then appends it to the form right before submission.
这篇关于使用jQuery将JSON附加到表单并提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文