![](/img/trans.png)
[英]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.