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

PhoneGap应用无法向SQL提交数据——deviceready事件问题求助

解决PhoneGap应用数据无法提交的问题

看起来你遇到的核心问题有几个:deviceready事件绑定错误、AJAX异步执行导致提前跳转,还有可能的PhoneGap域名白名单配置缺失。咱们一步步来解决:

1. 修复deviceready事件绑定

首先,你之前的代码里有个低级错误:绑定事件时用的是checkSubmit,但函数定义写成了Checksubmit(大小写不一致),这直接导致回调不会执行!另外,PhoneGap应用绝对不能用body onload来触发初始化代码——必须等deviceready事件触发后,才能执行任何依赖PhoneGap环境的代码(哪怕是localStorage,虽然浏览器也支持,但规范上必须这么做)。

正确的绑定方式应该是这样:

<script>
// 确保函数名大小写一致
function checkSubmit() {
  var todayNum = Number(new Date());
  var storedDate = localStorage.getItem("storedDate");
  var subDelay = 60000;
  var diff = todayNum - storedDate;

  if (!storedDate || storedDate === null || diff > subDelay) {
    localStorage.setItem("storedDate", todayNum);
    
    // 这里不需要嵌套$(function()),deviceready触发时DOM已加载完成
    $('form').submit(function(e){
      // 先阻止表单默认提交行为
      e.preventDefault();
      
      var postData = $(this).serialize();
      $.ajax({
        type: 'POST',
        data: postData,
        url: 'http://mydblocation.com/sqlin.php',
        success: function(data){
          console.log(data);
          // 仅在提交成功后提示并跳转
          alert("Thanks for your submission!");
          window.location = "index.html";
        },
        error: function(xhr, status, error){
          console.log('Error details:', status, error);
          alert('There was an error adding your submission, please try again later.');
        }
      });
    });
  } else {
    alert("You've already submitted! You will be able to submit again in 1 minute.");
    window.location = "index.html";
  }
}

// 正确绑定deviceready事件,确保PhoneGap环境就绪后执行代码
document.addEventListener("deviceready", checkSubmit, false);
</script>

2. 修正AJAX异步执行问题

你原来的代码在调用$.ajax后立刻执行alert和window.location,但AJAX是异步操作——这意味着跳转发生时,数据还没来得及提交到服务器!必须把跳转逻辑放在success回调里,确保只有当服务器确认接收数据后,才跳转到首页。

3. 配置PhoneGap域名白名单

这是打包后常见的坑:PhoneGap默认会限制应用访问外部域名,你需要在config.xml里添加允许访问目标服务器的规则:

<!-- 允许访问你的数据库服务器域名 -->
<access origin="http://mydblocation.com" />
<!-- 针对iOS的额外导航权限配置 -->
<allow-navigation href="http://mydblocation.com/*" />
<!-- 针对Android的额外意图权限配置 -->
<allow-intent href="http://mydblocation.com/*" />

同时,在HTML的<head>里添加Content-Security-Policy元标签,允许AJAX请求到目标域名:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' http://mydblocation.com; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';">

4. 移除body的onload属性

把<body onload="checkSubmit()">改成普通的<body>,因为我们已经通过deviceready事件触发初始化代码了。

最后检查几个细节

  • 确认你的PhoneGap项目已安装cordova-plugin-whitelist插件(白名单插件,默认已包含,但最好手动验证)
  • 测试时打开设备调试控制台(比如Chrome远程调试),查看是否有报错信息,这能帮你快速定位剩余问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:36:40