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

提交HTML/CSS/JS表单数据至谷歌表格时出现Failed to fetch错误的排查求助

提交HTML/CSS/JS表单数据至谷歌表格时出现Failed to fetch错误的排查求助

大家好,我正在开发一个签证积分计算器的第一步表单,打算把用户填写的数据提交到谷歌表格中,但每次点击提交按钮都会触发Failed to fetch错误,试了好几种方法都没解决,想请各位帮忙排查一下问题!

以下是我的step1.html完整代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Visa Points Calculator</title>
    <link rel="stylesheet" href="bootstrap.css">
    <link rel="stylesheet" href="bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
</head>
<body class="bg-light">
    <div class="container py-5">
        <div class="text-center">
            <h1>Visa Points Calculator Step-1</h1>
        </div>
        
        <form id="visaForm">
            <div class="row">
            <div class="col-md-6">
            <div class="form-group">
                <label for="candidateName">Candidate's Name:</label>
                <input type="text" class="form-control" id="candidateName" required>
            </div>

            <div class="form-group">
                <label for="contactNumber">Contact Number:</label>
                <input type="tel" class="form-control" id="contactNumber" required>
            </div>

            <div class="form-group">
                <label for="dob">Date of Birth:</label>
                <input type="date" class="form-control" id="dob" required>
            </div>

            <div class="form-group">
                <label for="email">Email ID:</label>
                <input type="email" class="form-control" id="email" required>
            </div>

            <div class="form-group">
                <label>Highest Education:</label><br>
                <input type="radio" name="education" value="10th"> 10th<br>
                <input type="radio" name="education" value="12th"> 12th<br>
                <input type="radio" name="education" value="Graduate"> Graduate<br>
                <input type="radio" name="education" value="Postgraduate"> Postgraduate<br>
                <input type="radio" name="education" value="Doctorate"> Doctorate<br>
            </div>

            <div class="form-group">
                <label for="degree">Educational Degrees:</label>
                <input type="text" class="form-control" id="degree">
            </div>

            <div class="form-group">
                <label>Assets:</label><br>
                <input type="checkbox" value="Irrigation Land"> Irrigation Land<br>
                <input type="checkbox" value="Commercial Land"> Commercial Land<br>
                <input type="checkbox" value="Apartment or Flat"> Apartment or Flat<br>
                <input type="checkbox" value="House"> House<br>
            </div>
            </div>

            <div class="col-md-6">
            <div class="form-group">
                <label for="currentVisaCountry">Current Visa Country(If any):</label>
                <select class="form-control" id="currentVisaCountry">
                    
                </select>
            </div>

            <div class="form-group">
                <label for="newVisaCountry">Want a visa to:</label>
                <select class="form-control" id="newVisaCountry">
                    
                </select>
            </div>

            <div class="form-group">
                <label for="visaRejectionCountries">Visa Rejection Countries(If any):</label>
                <select class="form-control" id="visaRejectionCountries">
                    
                </select>
            </div>

            <div class="form-group">
                <label for="lastVisaRejectionDate">Last Visa Rejection Date(If any):</label>
                <input type="date" class="form-control" id="dob" required>
            </div>

            <div class="form-group">
                <label>Profession:</label><br>
                <input type="radio" name="profession" value="Student" onclick="toggleIncomeFields(false)"> Student<br>
                <input type="radio" name="profession" value="Businessman" onclick="toggleIncomeFields(true)"> Businessman<br>
                <input type="radio" name="profession" value="Salaried" onclick="toggleIncomeFields(true)"> Salaried Employee<br>
            </div>

            <div id="incomeFields" style="display: none;">
                <div class="form-group">
                    <label for="monthlyIncome">Monthly Income(In Indian Rupees):</label>
                    <input type="text" class="form-control" id="monthlyIncome">
                </div>
                <div class="form-group">
                    <label>Income Type:</label><br>
                    <input type="checkbox" value="Business"> Business<br>
                    <input type="checkbox" value="Salaried"> Salaried<br>
                    <input type="checkbox" value="Other"> Other<br>
                </div>
            </div>

            </div>
            </div>

            <div style="text-align: center;">
                <button type="submit" class="btn btn-primary">Step-2</button>
            </div>
        </form>
    </div>

    <script>
        const countries = ["None", "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Argentina", "Australia", "Austria", "Bangladesh", "Belgium", "Brazil", "Canada", "China", "Denmark", "Egypt", "Finland", "France", "Germany", "India", "Italy", "Japan", "Mexico", "Netherlands", "Norway", "Pakistan", "Russia", "Saudi Arabia", "South Africa", "Spain", "Sweden", "Switzerland", "United Kingdom", "United States"];
        
        function populateCountries(selectId) {
            const selectElement = document.getElementById(selectId);
            countries.forEach(country => {
                const option = document.createElement('option');
                option.value = country;
                option.textContent = country;
                selectElement.appendChild(option);
            });
        }

        populateCountries('currentVisaCountry');
        populateCountries('newVisaCountry');
        populateCountries('visaRejectionCountries');

        function toggleIncomeFields(show) {
            document.getElementById('incomeFields').style.display = show ? 'block' : 'none';
        }

        document.getElementById('visaForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(e.target);
    let data = {};

    // Convert FormData to JSON Object
    formData.forEach((value, key) => {
        if (data[key]) {
            if (Array.isArray(data[key])) {
                data[key].push(value);
            } else {
                data[key] = [data[key], value];
            }
        } else {
            data[key] = value;
        }
    });

    // Collect checked checkboxes manually
    data['assets'] = Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(cb => cb.value);

    fetch('https://script.google.com/macros/s/AKfycbxOF8FLSlEd1sVmineXKQtph2Ix1RokQcJ3VuCYR3veLyi7xo98h3eW0zTvQN_fFnNK/exec', {
        method: 'POST',
         mode: 'cors',  // Ensure CORS mode is enabled
        body: JSON.stringify(data),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(responseJson => {
        if (responseJson.result === "success") {
            alert('Data submitted successfully');
            window.location.href = '/stepcountries.html';
        } else {
            alert('Error in Google Apps Script: ' + JSON.stringify(responseJson));
        }
    })
    .catch(error => {
        console.error('Fetch error:', error);
        alert('Failed to submit data: ' + error.message);
    });
});
    </script>
</body>
</html>

补充说明一下:

  • 我已经部署了谷歌Apps Script作为接收数据的后端,并且用了部署后的URL
  • 表单数据会先转成JSON格式,也手动处理了复选框的资产数据收集
  • 特意设置了mode: 'cors',但还是没能解决问题

现在每次提交时,控制台都会输出Failed to fetch的错误,弹窗也只会提示提交失败。有没有大佬能帮我分析下可能的问题点?比如CORS配置、Apps Script的部署设置、表单数据格式是否有问题,或者其他我没注意到的细节?

备注:内容来源于stack exchange,提问作者Dronal Bhardwaj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:23:08