Ajax控制台显示参数正常但PHP未接收POST参数问题
问题:POST参数无法被PHP后端获取
控制台已输出正确的请求URL和category参数值,但PHP返回“Script is running”后提示“No category parameter received”,无法获取POST传递的参数。
原代码
前端Ajax代码
<script> function loadSubcategories() { var categorySelect = document.getElementById("category"); var selectedCategory = categorySelect.value; // Create an XMLHttpRequest object var xhr = new XMLHttpRequest(); // Define the PHP file to call and the HTTP request method var url = "cgi-bin/get_subcategories.php"; var method = "POST"; // Set up the request xhr.open(method, url, true); // Set the request header (if needed) // Define the callback function xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // Update the subcategory dropdown with the response from the PHP file var subcategorySelect = document.getElementById("subcategory"); subcategorySelect.innerHTML = xhr.responseText; alert(xhr.responseText); return; } }; // Send the request with the selected category console.log("XHR URL: " + url); console.log("XHR Data: " + "category=" + selectedCategory); xhr.send("category=" + selectedCategory); } </script>
后端PHP代码
<?PHP echo "Script is running"; if ($_SERVER["REQUEST_METHOD"] == "POST") { $category = $_POST['category']; echo $category; } } else { // Handle the case when "category" is not set echo "No category parameter received."; } ?>
问题原因及修复方案
- 缺少POST请求头:发送表单格式的POST数据时,必须设置
Content-Type为application/x-www-form-urlencoded,否则PHP无法自动解析$_POST数组。原前端代码注释掉了请求头设置,这是核心问题。 - PHP语法错误:原PHP代码中
if ($_SERVER["REQUEST_METHOD"] == "POST")分支后多了一个多余的},导致逻辑结构混乱,即使参数正确也会执行错误分支。
修正后的代码
前端修正版
<script> function loadSubcategories() { var categorySelect = document.getElementById("category"); var selectedCategory = categorySelect.value; var xhr = new XMLHttpRequest(); var url = "cgi-bin/get_subcategories.php"; var method = "POST"; xhr.open(method, url, true); // 必须设置Content-Type头,确保PHP能解析POST参数 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var subcategorySelect = document.getElementById("subcategory"); subcategorySelect.innerHTML = xhr.responseText; alert(xhr.responseText); return; } }; console.log("XHR URL: " + url); console.log("XHR Data: " + "category=" + selectedCategory); xhr.send("category=" + selectedCategory); } </script>
后端修正版
<?PHP echo "Script is running"; if ($_SERVER["REQUEST_METHOD"] == "POST") { // 先判断参数是否存在,避免未定义索引警告 if(isset($_POST['category'])){ $category = $_POST['category']; echo $category; } else { echo "No category parameter received."; } } else { echo "Request method is not POST."; } ?>
内容的提问来源于stack exchange,提问作者John B
相关产品推荐
相关产品推荐

