【发布时间】:2025-11-25 02:00:01
【问题描述】:
我有我的表单和我的 ajax 布局,但我不知道如何使用 ajax 提交表单。我试过$('#testform').submit(),但是当我用提交包裹它时它没有调用我的ajax。我可能做错了。如何让我的表单通过 ajax 提交而不是定期提交?
<form id="testform" action="https://example.com/api/payments/" method="post">
Name<input type="text" name="name" id="name">
Card Number <input type="text" name="card_number" id="card_number" maxlength="16">
Exp Month <input type="text" name="exp_month" id="exp_month">
Exp Year <input type="text" name="exp_year" id="exp_year">
CVC <input type="text" name="cvc" id="cvc" maxlength="3">
Amount <input type="text" name="amount" id="amount">
<input type="submit" id="submit">
frm = $('#testform');
frm.submit(function(ev)
{
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "html",
//Set the HTTP headers for authentication
beforeSend: function (xhr) {
xhr.setRequestHeader('api_key', 'tiyndhinzrkzti5ody0');
xhr.setRequestHeader('email', 'example@example.com');
},
//Serialize the data sent from the form inputs
data: frm.serialize(),
success: function(data) {
$('#return').append(data);
}
});
ev.preventDefault();
});
【问题讨论】:
-
frm = $('testform');应该是frm = $('#testform'); -
谢谢。我只是在代码中输入错误
-
代码看起来不错。我的假设是身份验证不起作用,或者您遇到了 CORS 问题。
标签: javascript php jquery ajax forms