使用jQuery序列化表单后PHP后端处理失败问题求助
问题分析与修复方案
我一眼就看到了核心问题:你的PHP代码里依赖$_POST['submit']来触发表单数据的处理逻辑,但jQuery的$('#qform').serialize()不会包含submit按钮的参数——因为你用event.preventDefault()阻止了表单的默认提交行为,submit按钮并没有被当作表单提交的一部分,所以$_POST['submit']根本不存在,导致后面创建Question对象、填充数据的代码完全没执行,$questions是空数组,最后save_to_DAO()里因为$this->questions为空直接跳过了保存逻辑。
除此之外还有两个小问题需要一并修复:
修复步骤
1. 移除或调整$_POST['submit']的判断
既然已经用$_SERVER['REQUEST_METHOD'] == 'POST'判断了是POST请求,完全不需要再依赖submit参数来触发逻辑。直接把PHP里的这段判断去掉:
if(isset($_POST['submit'])) { // ... 原来的创建Question的代码 }
改成直接执行里面的逻辑,或者如果一定要保留判断,可以在AJAX请求里手动添加submit参数:
$.post("create_quiz_op.php", $('#qform').serialize() + "&submit=1", function(response) { getQuestions(displayQuestions); } );
2. 修正jQuery的回调函数写法
你现在的回调getQuestions(displayQuestions)会立即执行这个函数,而不是等到AJAX请求完成后再执行。正确的写法是用匿名函数包裹,或者直接传函数引用:
function postQuestion(){ $('.js-submit').click(function(event){ event.preventDefault(); $.post("create_quiz_op.php", $('#qform').serialize(), function(response) { getQuestions(displayQuestions); } ); }); }
3. 修复异常类的大小写问题
PHP里的异常类是Exception(大写E),你代码里的catch (exception $e)会导致无法正确捕获异常,改成:
catch (Exception $e) { die ('ERROR: ' . $e->getMessage() . $this->questions); return false; }
修改后的关键代码示例
调整后的PHP处理代码
if ($_SERVER['REQUEST_METHOD'] == 'POST') { $questions = []; $cq = new CreateQuizController(); // 直接处理表单数据,不再依赖submit参数 $question = new Question(); $question->set_id($_POST['id']); $question->set_question($_POST['question']); for ($j = 0; $j < count($_POST['answers']); $j++) { $question->set_answer($_POST['answers'][$j]); } $question->set_right_answer($_POST['right_answer']); $questions[] = $question; $cq->set_questions($questions); if($cq->save_to_DAO()) { print_r(json_encode($cq->get_from_DAO())); print_r("\n"); } else { echo "Problema"; } } ?>
修正后的jQuery代码
function postQuestion(){ $('.js-submit').click(function(event){ event.preventDefault(); $.post("create_quiz_op.php", $('#qform').serialize(), function(response) { // 确保在AJAX返回后再执行后续逻辑 getQuestions(displayQuestions); } ); }); }
修复异常捕获的save_to_DAO方法
public function save_to_DAO() { if ($this->questions) { try { $data = json_encode($this->questions); $prev = $this->get_from_DAO(); $form = $this->questions; if(isset($prev)){ $arr = array_merge( $prev, $form ); $data = json_encode($arr); } $w = file_put_contents('questions.json', $data); if($w && $w > 0) { return true; } } catch (Exception $e) { // 修正为大写的Exception die ('ERROR: ' . $e->getMessage() . $this->questions); return false; } } // 新增:如果$this->questions为空,返回false或者做对应处理 return false; }
内容的提问来源于stack exchange,提问作者ffuentes
相关产品推荐
相关产品推荐

