[英]Is there a way to modify the form data that will be sent to the server before submitting it?
[英]Is there a way in JavaScript to retrieve the form data that *would* be sent with a form without submitting it?
如果我有一个 HTML 表格,假设...
<form id='myform'>
<input type='hidden' name='x' value='y'>
<input type='text' name='something' value='Type something in here.'>
<input type='submit' value='Submit'>
</form>
...然后我使用 jQuery 来响应表单提交事件,例如
$('#myform').submit(function() {
...
return false;
});
现在假设我想以 AJAX 调用的形式提交表单,而不是以“传统”方式(作为新页面)实际提交。 有没有一种简单的方法来获取包含将要发送的数据的 JS object,我可以将其传递给$.post()
? 所以在上面的例子中,它看起来像......
{
x: 'y',
something: 'Type something in here.'
}
还是我必须自己烤?
由于您已经在使用 jQuery,请使用jQuery.serialize()
。
$('#myform').submit(function() {
var $form = $(this);
var data = $form.serialize();
// ...
});
请参阅serialize()
方法。
$('#myform').submit(function() {
jQuery.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function () {
//
}
});
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.