ajax的提交条件



我有一个html表单和一个ajax脚本,它在不刷新页面的情况下发送它,我还检查了两个相同的发布日期是否没有进入数据库,但当我点击提交时,它仍然会写"提交表格";,帮我修

这是我的脚本

<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#my_form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/main/store',
data: $('#my_form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>

在不知道您在ajax请求中发送的数据或如何在服务器上处理请求的情况下,您需要调整以下半伪代码以满足您的需求,或者使用其中的一些简单地设计您自己的解决方案。

从本质上讲,ajax回调应该从服务器接收数据。在您的代码中,回调没有提供任何参数-在success: function () {...中添加一个类似于success: function(r) {...的变量,因此服务器的响应现在被分配给r

通过该响应,您现在可以根据r的值向用户显示不同的消息。例如:

<?php
/****************
/main/store
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){

require 'dbconn.php';


/* example pseudo function to test date */
function date_is_duplicate( $date ){
global $db; // your db connection variable

$sql='select * from `TABLE` where `DATEFIELD`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$date);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->free_result();
$stmt->close();

/*
..... etc, etc, etc and return a value to be used in ajax callback 
If there are ZERO rows send ZERO as response - or more than ZERO means duplicate
*/
return $rows;
}


/* Do the Duplicate Date search tests */
$result=date_is_duplicate( $_POST['date'] );
if( $result ) exit( $result );
else{
/* 
do other exciting things - add to db etc etc but SEND a response to the
ajax callback so that it can display the correct message.
send ZERO as response.
*/
}
}
?>

然后,修改后的javascript有一个响应变量,可以帮助派生程序逻辑:-

$(function(){
$('#my_form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/main/store',
data: $('#my_form').serialize(),
success:function(r) {

let message='OK, form was submitted';
if( Number(r)===1 )message='Bogus, duplicate date detected';

alert(message);
}
});
});
});

要发送回的数据结构要健壮得多,应该是JSON,而不是单个整数——这是为了说明这个概念而匆忙拼凑起来的。使用JSON,您可以为解决方案设计更大的复杂性

最新更新