开发者

Use jQuery to attach JSON to a form and submit it

开发者 https://www.devze.com 2022-12-10 03:27 出处:网络
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.

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" metho开发者_Go百科d="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.

0

精彩评论

暂无评论...
验证码 换一张
取 消