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

如何在HTML中将&替换为%20以实现WhatsApp订单消息正常发送

解决WhatsApp订单消息中出现&符号的问题

问题根源在于你的表单直接用GET方式提交时,producto1、producto2这类额外参数会被自动用&拼接在URL里,而WhatsAPI只会读取text参数的内容,其他参数的&分隔符会被当成文本显示在消息中。

修复方案

  1. 移除无用的空隐藏字段,避免干扰请求逻辑;
  2. 用JavaScript拦截表单默认提交行为,手动拼接订单内容并做URL编码(自动将空格转为%20),再构造正确的WhatsApp跳转链接。

完整修复代码

<form id="whatsapp-order-form" style="text-align: center;">
    <input type="hidden" name="phone" value="56987955586" />
    <ul style="list-style: none; padding: 0; display: grid; grid-gap: 10px;">
        <li style="margin-bottom: 10px;">
            <span style="font-weight: bold; display: inline-block; vertical-align: middle;">Producto 1:</span>
            <input type="number" name="producto1" min="0" value="0" style="margin-left: 5px; width: 70px; display: inline-block; vertical-align: middle;" />
        </li>
        <li style="margin-bottom: 10px;">
            <span style="font-weight: bold; display: inline-block; vertical-align: middle;">Producto 2:</span>
            <input type="number" name="producto2" min="0" value="0" style="margin-left: 5px; width: 70px; display: inline-block; vertical-align: middle;" />
        </li>
    </ul>
    <button type="submit" style="background-color: #00c853; color: #ffffff; font-size: 20px; border-radius: 40px; border: none; padding: 15px 30px; margin: 20px auto; display: block; text-transform: uppercase; font-weight: bold;">
        Enviar Pedido por WhatsApp
    </button>
</form>
<style>
@media (min-width: 501px) {
    ul {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (min-width: 801px) {
    ul {
        grid-template-columns: repeat(3, 1fr);
    }
}
</style>
<script>
document.getElementById('whatsapp-order-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    // 获取表单数据
    const phone = this.querySelector('[name="phone"]').value;
    const producto1 = this.querySelector('[name="producto1"]').value;
    const producto2 = this.querySelector('[name="producto2"]').value;
    
    // 拼接订单消息
    let message = `Pedido:\n`;
    if (producto1 > 0) message += `Producto 1: ${producto1}\n`;
    if (producto2 > 0) message += `Producto 2: ${producto2}\n`;
    
    // URL编码自动转换空格为%20
    const encodedMessage = encodeURIComponent(message);
    
    // 构造链接并跳转
    const whatsappUrl = `https://api.whatsapp.com/send?phone=${phone}&text=${encodedMessage}`;
    window.open(whatsappUrl, '_blank');
});
</script>

核心说明

  • encodeURIComponent()会自动处理所有URL特殊字符,包括将空格转为%20,完全适配WhatsApp的链接要求;
  • 手动构造仅包含phone和text参数的链接,彻底避免多余参数带来的&符号问题;
  • 仅添加数量大于0的产品到消息中,让订单内容更简洁清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:53:24