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

Ajax提交函数失效求助:无法向PHP发送表单数据

解决Ajax Submit事件无法触发的问题

我帮你排查了代码里的几个关键问题,这应该就是submit事件没生效的核心原因:

1. jQuery选择器匹配错误

你的表单设置的是name="formReportStolen",但绑定事件时用的是$('#formReportStolen')——这是ID选择器,只会匹配带id="formReportStolen"的元素,完全不会识别name属性。

两种解决方式选其一即可:

  • 给表单添加id属性:
<form id="formReportStolen" name="formReportStolen" action="PublicReportStolenDAO.php" method="POST" enctype="multipart/form-data">
  • 改用name属性选择器:
$('form[name="formReportStolen"]').on('submit', function(e){

2. 重复引入jQuery导致冲突

你的HTML头部同时加载了两个不同版本的jQuery:

<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

这会导致jQuery对象被后加载的版本覆盖,之前的事件绑定逻辑直接失效。只保留一个版本就行,推荐留下较新的3.3.1版本,删掉第一个引入代码。

3. 确保DOM加载完成后再绑定事件

你的脚本直接写在页面中,如果脚本执行时表单元素还没渲染到DOM里,jQuery根本找不到目标元素,事件绑定自然不会生效。

把submit事件的绑定代码放到$(document).ready()里,确保DOM完全加载后再执行:

$(document).ready(function(){
    $('#formReportStolen').on('submit', function(e){
        var formData = new FormData(this);
        formData.append("lat", markerLatitude);
        formData.append("lng", markerLongitude);
        // 顺便修正这里的笔误:把markerLongitude改成markerLatitude
        console.log("Latitude: " + markerLatitude + " Longitude:" + markerLongitude+ " DATA SENT TO PHP");
        e.preventDefault();
        $.ajax({
            url: 'PublicReportStolenDAO.php',
            method: "POST",
            data: formData,
            contentType: false,
            cache: false,
            processData: false,
            success:function(echoedMsg) {
                if (echoedMsg == "True") {
                    alert("Successfully reported.");
                }
            }
        });
    });
});

把以上问题全部修复后,你的submit事件应该就能正常触发,表单数据也能通过Ajax顺利发送到PHP了。

内容的提问来源于stack exchange,提问作者Joshua Best

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:36:37