![](/img/trans.png)
[英]Using Ajax and jQuery to check if file exists - always returns 200 response
[英]jQuery AJAX response always returns blank message
嗨,我正在尝试制作HTML表单,并且需要在执行表单操作之前对其进行验证。 但是AJAX响应总是返回空消息吗?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
} else {
console.log(msg);
}
}).fail(function() {
// Catch ajax errors here
console.log('AJAX error');
});
});
});
PHP:
$post = (!empty($_POST)) ? true : false;
if ($post) {
$orderid = stripslashes($_POST['orderid']);
$amount = stripslashes($_POST['amount']);
$betingelser = stripslashes($_POST['betingelser']);
$error = ''; // Check ordreid
if (!$orderid) {
$error. = 'Venligst indtast dit ordreid.<br />';
} // Check amount
if (!$amount) {
$error. = 'Venligst indtast et beløb.<br />';
}
if (!$error) {
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.
'</div>';
}
}
谁能告诉我怎么了?
您位于submit
按钮的click
处理程序中。 您正在调用$(this).serialize()
, this
是该提交按钮。 在提交按钮上调用序列化将返回一个空字符串。
因此,您没有将任何数据传递到服务器。 在服务器端执行的第一件事是检查empty($_POST)
, 它将为 ,因此, if ($post)
为false,则不会执行任何服务器端代码。
您需要序列化表单 ,而不是提交按钮。
一个简单的解决方案是序列化表单本身。
str = $('"#ajax-payment-form').serialize()
但实际上,更大的问题是您绑定了click
提交按钮,而不是绑定到表单本身上的submit
事件。
而不是这种复杂的表单提交方式...
$("#ajax-payment-form input[type='submit']").click(function(e) {
只要这样做:
$("#ajax-payment-form").submit(function (e) {
试试这个在jQuery中:
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this,
success: function(msg){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
}
else {
console.log(msg);
}
}
error: function(msg){
// if call fails or any error occurs
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.