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

如何将HTML表单数据以JSON请求提交至HTTP主机并实现SMS发送功能?

Got it, let's break this down step by step to get your SMS sending feature up and running. I'll walk you through both the frontend form handling and a simple backend example to send the SMS and display the response to users.

实现表单提交发送SMS并展示响应的完整方案

1. 前端HTML表单与提交逻辑

First, here's a sample form based on common SMS needs — you can tweak the fields to match your actual requirements:

<!DOCTYPE html>
<html>
<head>
    <title>SMS Sender</title>
    <style>
        .response-box { margin-top: 20px; padding: 12px; border-radius: 4px; display: none; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <form id="smsForm">
        <label for="targetPhone">目标手机号:</label>
        <input type="tel" id="targetPhone" name="targetPhone" required placeholder="例如:+8613XXXXXXXXX"><br><br>
        
        <label for="smsText">短信内容:</label>
        <textarea id="smsText" name="smsText" rows="4" required placeholder="输入要发送的短信内容"></textarea><br><br>
        
        <button type="submit">发送短信</button>
    </form>

    <!-- 用于展示响应的容器 -->
    <div id="responseBox" class="response-box"></div>

    <script>
        const form = document.getElementById('smsForm');
        const responseBox = document.getElementById('responseBox');

        form.addEventListener('submit', async (e) => {
            e.preventDefault(); // 阻止表单默认跳转行为

            // 收集表单数据并按指定格式构造请求体
            const formData = new FormData(form);
            const requestBody = {
                phone: formData.get('targetPhone'),
                message: formData.get('smsText')
                // 按需添加其他必填字段,比如模板ID、签名等
            };

            try {
                // 发送请求到后端接口(避免前端直接调用第三方API暴露密钥)
                const res = await fetch('/api/send-sms', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestBody),
                });

                const responseData = await res.json();

                // 根据响应格式展示结果
                responseBox.style.display = 'block';
                if (responseData.code === 200) {
                    responseBox.className = 'response-box success';
                    responseBox.textContent = `✅ 短信发送成功!响应ID: ${responseData.data.id}, 状态: ${responseData.data.status}`;
                } else {
                    responseBox.className = 'response-box error';
                    responseBox.textContent = `❌ 发送失败: ${responseData.msg}`;
                }
            } catch (err) {
                responseBox.style.display = 'block';
                responseBox.className = 'response-box error';
                responseBox.textContent = '⚠️ 请求异常,请检查网络或稍后重试';
                console.error('请求出错:', err);
            }
        });
    </script>
</body>
</html>

2. 后端接口实现(Node.js/Express示例)

You'll need a backend to handle the SMS request (front-end calls to third-party SMS APIs will expose your private keys). Here's a simple Express example — replace the SMS service logic with your provider's API specs:

const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const PORT = 3000;

app.use(bodyParser.json());
app.use(express.static('public')); // 托管前端静态文件

// 替换为你的SMS服务商配置
const SMS_SERVICE = {
    apiUrl: 'https://your-sms-provider.com/api/send',
    apiKey: 'YOUR_PRIVATE_API_KEY',
    senderId: 'YOUR_SENDER_ID'
};

app.post('/api/send-sms', async (req, res) => {
    const { phone, message } = req.body;

    try {
        // 按服务商要求的格式构造请求
        const smsRequest = {
            to: phone,
            content: message,
            api_key: SMS_SERVICE.apiKey,
            sender: SMS_SERVICE.senderId
            // 添加服务商要求的其他字段,比如模板ID
        };

        // 调用SMS服务商API
        const smsRes = await axios.post(SMS_SERVICE.apiUrl, smsRequest);

        // 按你需要的格式返回响应给前端
        res.json({
            code: 200,
            msg: 'success',
            data: {
                id: smsRes.data.message_id,
                status: smsRes.data.status,
                sendTime: new Date().toISOString()
            }
        });
    } catch (err) {
        // 处理错误响应
        res.status(500).json({
            code: 500,
            msg: err.response?.data?.error || '短信服务调用失败'
        });
    }
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

3. 关键调整提示

  • 请求格式适配:Modify the requestBody (front-end) and smsRequest (back-end) to match the exact field requirements of your SMS service provider.
  • 响应格式对齐:Update the front-end response parsing logic to match the structure of the response you expect from your backend/SMS service.
  • Security First:Never expose your SMS service API keys in front-end code — always route requests through a backend.
  • Phone Number Validation:Add regex validation in the front-end to ensure users input valid phone numbers before submission.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:53:41