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

Wix表单提交至Google Sheet的AJAX请求代码编写遇阻

解决Wix表单同步到Google Sheet的AJAX请求问题

我来帮你搞定这个同步表单数据的问题!你已经完成了Google Web App的创建,接下来只需要正确构造AJAX请求就行,分两种场景给你具体代码:

场景1:你在Wix中嵌入了自定义HTML表单(用了jQuery选择器$('form#test-form'))

直接用jQuery的AJAX提交,注意跨域问题用jsonp处理(Google Web App天然支持这种方式),代码如下:

// 放在Wix页面的代码编辑器中,确保页面加载完成后执行
$w.onReady(function () {
  const $form = $('form#test-form');

  $form.on('submit', function(e) {
    e.preventDefault(); // 阻止默认的表单跳转行为

    // 序列化表单数据(自动把表单字段转成key=value格式)
    const formData = $(this).serialize();

    $.ajax({
      url: 'https://script.google.com/macros/s/abc.../exec', // 替换成你的Web App URL
      type: 'POST',
      data: formData,
      dataType: 'jsonp', // 解决跨域请求限制
      success: function(response) {
        console.log('数据同步成功!', response);
        // 这里可以添加成功提示,比如显示感谢语
        $form[0].reset(); // 清空表单
      },
      error: function(xhr, status, error) {
        console.error('提交失败,请检查:', error);
        // 这里添加错误提示
      }
    });
  });
});

配套的Google Apps Script(doPost函数)

确保你的Web App脚本里的doPost函数能正确接收并写入数据:

function doPost(e) {
  // 替换成你的表格名称,比如"表单数据"
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  const formParams = e.parameter; // 获取表单提交的所有字段

  // 按你需要的顺序写入表格,字段名要和表单的name属性对应
  // 比如表单里有name="username"、name="email"、name="message"
  sheet.appendRow([formParams.username, formParams.email, formParams.message]);

  // 返回成功响应,支持jsonp回调
  return ContentService.createTextOutput(JSON.stringify({status: 'success'}))
    .setMimeType(ContentService.MimeType.JSON);
}

场景2:你用的是Wix自带的表单组件

如果是Wix官方的表单组件,不能直接用jQuery选择器,得用Wix的Form API来处理,代码示例:

$w.onReady(function () {
  // 替换成你的Wix表单组件ID
  $w('#testForm').onSubmit((event) => {
    event.preventDefault(); // 阻止默认提交行为

    // 获取表单字段数据
    const formFields = event.fields;
    const postData = new URLSearchParams();

    // 把Wix表单的字段转换成POST需要的格式
    for (const fieldId in formFields) {
      postData.append(fieldId, formFields[fieldId].value);
    }

    // 用fetch API提交(比AJAX更现代)
    fetch('https://script.google.com/macros/s/abc.../exec', {
      method: 'POST',
      body: postData,
      mode: 'cors' // Google Web App允许跨域请求
    })
    .then(() => {
      console.log('数据同步成功!');
      $w('#testForm').reset(); // 重置表单
    })
    .catch(error => {
      console.error('提交失败:', error);
    });
  });
});

关键注意事项

  • Web App部署设置:一定要在部署时选择「执行权限:任何人,甚至匿名」,否则Wix前端无法发起请求。
  • 字段名对应:表单的name属性(自定义表单)或字段ID(Wix自带表单)要和Google脚本里的formParams.xxx完全一致,否则会拿不到数据。
  • 测试调试:打开浏览器的开发者工具(F12),查看Console面板的日志,能快速定位提交失败的原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:12:47