使用Fetch提交数据时PHP的POST数组为空问题求助
问题:POST数据无法进入PHP数组,请求Payload正常但$_POST/$_REQUEST为空
使用XAMPP搭建本地站点,开发Quiz更新功能时遇到问题:前端FormData和请求Payload都显示数据完整,但PHP端var_dump($_POST)和var_dump($_REQUEST)结果为空。另外有个奇怪的现象,另一个文件同样$_POST为空却能更新数据库,数据库连接正常(能正常读取数据)。
相关代码
处理请求的JavaScript代码
function saveQuiz() { const quizID = "<?php echo $quizid; ?>"; const quizName = document.getElementById("quiz_name").value; const formData = new URLSearchParams(); formData.append('quizName', quizName); formData.append('quizID', quizID); const questionTexts = document.querySelectorAll('.question-text'); // Loop through the question texts and append them to formData questionTexts.forEach((textarea, index) => { formData.append(`question_texts[${index}]`, textarea.value); }); console.log('FormData:', formData); for (const pair of formData.entries()) { console.log(pair[0] + ': ' + pair[1]); }//prints everything correctly fetch('updateQuiz.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData }) .then(response => { console.log('submitted', response); }) .catch(error => { console.error('error: ', error); }); window.location.href = "../quiz/quizzesOverviewFaculty.php"; }
处理逻辑的updateQuiz.php文件
<?php var_dump($_REQUEST); session_start(); $host = "localhost"; $dbname = "course_resource_library"; $dbusername = "root"; $dbpassword = ""; //Creating connection to database $conn = mysqli_connect( hostname: $host, username: $dbusername, password: $dbpassword, database: $dbname ); if ($conn) { $quizID = $_POST['quizID']; $quizName = $_POST['quizName']; // Update the database with the new names $query = "UPDATE quiz SET quiz_name='$quizName' WHERE quiz_ID='$quizID'"; $result = mysqli_query($conn, $query); //Retrieve question IDs and texts sent from the client-side $questionIDs = $_POST['question_ids']; $questionTexts = $_POST['question_texts']; // Check if the arrays have the same length if (count($questionIDs) === count($questionTexts)) { // Loop through the question IDs and texts for ($i = 0; $i < count($questionIDs); $i++) { $questionID = $questionIDs[$i]; $questionText = $questionTexts[$i]; $updateQuery = "UPDATE questions SET question = '$questionText' WHERE question_ID = '$questionID'"; } // Check if the update was successful if ($conn->query($updateQuery) === TRUE) { // Successful update echo "Question with ID: $questionID updated successfully<br>"; } else { // Failed to update echo "Error updating question with ID: $questionID - " . $conn->error . "<br>"; } } if ($result) { // Update successful echo "Name updated successfully"; echo $quizID; echo " "; echo $quizName; } else { // Error in updating echo "Error updating name: " . mysqli_error($conn); } } else { echo "error: " . mysqli_error($conn); } mysqli_close($conn); ?>
提供数据的HTML代码
<div class="container container-fluid"> <!-- This creates the thing in the middle that holds the info --> <div class="card h-4"> <div class="card-header text-dark" style = "background-color:#CEB888"> <div> <span style="font-size: x-large; margin-left: 20px;"><b>Quiz Name: </b></span> <input type="text" id="quiz_name" name="quiz_name" required="Yes" style="font-size: large;" value="<?php echo $quiz_name; ?>"> </div> </div> <div class="card-body"> <div class="card-body"> <div class="row"> <div class="card h-100 w-100"> <div class="card-body"> <!-- Loop through number of questions --> <?php // Assuming you have already retrieved questions and answers from the database // Repeat the loop for however many questions are in the quiz foreach ($data as $row) { $questionId = $row["question_ID"]; $questionText = $row["question"]; ?> <!-- Display questions using html --> <h5 class="card-title text-dark">Question <?php echo $questionId; ?></h5> <p class="card-text text-dark"></p> <br> <textarea class="form-control question-text" rows="5" name="questions[<?php echo $questionId; ?>]"><?php echo $questionText; ?></textarea> <br> <span style="font-size: large; color: grey;">Answers:</span> <br> <br> <div class="row"> <!--<input type="hidden" name="question_ids[]" value="<?php //echo $row["question_ID"]; ?>"> <input type="hidden" name="question_texts[]" value="<?php //echo $row["question"]; ?>">--> <!-- Use php to get the current answer questions --> <?php //repeat the loop for however many answers there are foreach ($data2 as $row2) { $answerId = $row2["question_ID"]; $answerText = $row2["answer_option"]; if($answerId === $questionId) { ?> <!-- Use html to display radio buttons and answers --> <span> </span> <!-- This will make sure the correct answer is selected --> <?php // check to see if current answer is the correct answer if($row2["correct_answer"] == "yes") { ?> <input type="radio" id="answer_<?php echo $answerId; ?>" name="question_<?php echo $questionId; ?>" value="<?php echo $answerId; ?>" required checked> <?php } else { ?> <input type="radio" id="answer_<?php echo $answerId; ?>" name="question_<?php echo $questionId; ?>" value="<?php echo $answerId; ?>" required="required"> <?php } ?> <span> </span> <input type="text" id="quiz_name" name="quiz_name" required="Yes" value="<?php echo $answerText; ?>" > <!-- End loop that goes through the questions --> <?php } } ?> </div> <!-- End the big php loop --> <?php } ?> </div> </div> </div> <br> <!-- Buttons at the bottom of the page --> <div class="row"> <div class="d-flex justify-content-start align-items-center"> <a class="nav-link text-light btn mr-2" href="#" style="background-color:#0C8CE9; height: 30pt;"><b>Create Next Question</b></a> <a class="nav-link text-light btn mr-2" style="background-color:#0C8CE9; height: 30pt;" onclick="saveQuiz()"><b>Save and Post</b></a> </div> <div class="d-flex justify-content-end align-items-center"> <a class="nav-link text-light btn" href="quizzesOverviewFaculty.php" style="background-color:#F54545; height: 30pt;"><b>Cancel</b></a> </div> </div> <!-- Buttons at bottom of page --> </div> </div> </div> </div>
问题排查与修复方案
1. 页面跳转中断请求
JavaScript最后执行的window.location.href会立即终止当前fetch请求,导致PHP无法完整接收数据,这是$_POST为空的核心原因。
修复: 将跳转逻辑移至fetch的then回调内,确保请求完成后再跳转:
fetch('updateQuiz.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData }) .then(response => { console.log('submitted', response); // 请求完成后再执行跳转 window.location.href = "../quiz/quizzesOverviewFaculty.php"; }) .catch(error => { console.error('error: ', error); });
2. PHP代码顺序错误
session_start();必须放在所有输出之前,当前代码先执行var_dump($_REQUEST)触发输出,会导致session初始化失败,同时可能影响全局变量读取。
修复: 将session_start();移至PHP代码最顶部:
<?php session_start(); var_dump($_REQUEST); // 后续代码...
3. 缺失question_ids数据
前端仅提交了question_texts,但PHP尝试读取$_POST['question_ids'],且HTML中对应的隐藏域被注释,需补充数据提交:
修复: 取消HTML中的注释,或在前端手动添加到FormData:
// 在前端saveQuiz函数中添加question_ids的提交 const questionIds = document.querySelectorAll('input[name="question_ids[]"]'); questionIds.forEach(input => { formData.append('question_ids[]', input.value); });
4. SQL注入风险
当前代码直接将用户输入拼接进SQL语句,存在严重安全隐患,必须使用预处理语句:
// 示例:更新quiz名称的预处理写法 $stmt = $conn->prepare("UPDATE quiz SET quiz_name=? WHERE quiz_ID=?"); $stmt->bind_param("si", $quizName, $quizID); $stmt->execute(); $stmt->close();
内容的提问来源于stack exchange,提问作者Amber
相关产品推荐
相关产品推荐

