You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP文件Undefined array key错误:AJAX POST请求参数无法获取

问题排查与修复方案

1. 阻止表单默认提交行为

表单的submit按钮点击后会触发默认页面刷新,直接中断AJAX请求。需要绑定事件阻止默认行为:

修改JS部分:

// 给表单添加id后绑定submit事件
$('#weatherForm').submit(function(e) {
    e.preventDefault(); // 阻止表单默认提交动作
    $.ajax({
        url: "../project1/php/weather.php",
        type: 'POST',
        dataType: 'json',
        data: {
            latitude: $('#latitude').val(),
            longitude: $('#longitude').val()
        },
        success: function (result) {
            console.log(JSON.stringify(result));
            if (result) {
                // 后续业务逻辑
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(JSON.stringify(errorThrown));
        }
    });
});

同时给HTML表单添加id:

<form method="POST" id="weatherForm">
    <input type="number" name="latitude" id="latitude" step="0.01"/>
    <input type="number" name="longitude" id="longitude" step="0.01"/>
    <input type="submit" value="submit">
</form>

2. 补全PHP脚本的返回逻辑

你的PHP仅设置了响应头,但未输出处理后的JSON数据,导致AJAX接收不到内容。同时建议增加参数校验避免报错:

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);

// 先校验参数是否存在
if (!isset($_REQUEST['latitude'], $_REQUEST['longitude'])) {
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(['error' => '缺少纬度或经度参数']);
    exit;
}

$url =
    'https://api.openweathermap.org/data/2.5/weather?lat=' .
    $_REQUEST['latitude'] .
    '&lon=' .
    $_REQUEST['longitude'] .
    '&appid=mykey';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);

$data = curl_exec($ch);
curl_close($ch);

$decode = json_decode($data, true);

header('Content-Type: application/json; charset=UTF-8');
echo json_encode($decode); // 输出最终JSON响应
?>

3. 验证AJAX请求路径

检查../project1/php/weather.php是否与当前页面的文件路径匹配。例如当前页面若在project1/目录下,路径应改为php/weather.php,路径错误会导致请求404,PHP脚本无法执行。

调试技巧

  • 打开浏览器开发者工具(F12)的Network标签,点击submit后查看AJAX请求的状态、发送的参数和响应内容,确认参数是否正常传递。
  • 取消PHP中var_dump($_REQUEST);的注释,直接查看请求携带的参数情况。

内容的提问来源于stack exchange,提问作者Kyle Ghilotti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:42:50