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

嵌入捐赠表单时source参数重复出现的问题排查与修复

问题分析与修复方案

问题原因

  • 变量作用域错误:全局变量results被赋值为正则表达式exec方法的返回数组(格式为["?source=xxx", "xxx"]),而非实际提取的source参数值。拼接URL时直接使用该数组,会导致数组转字符串后出现重复的?source=内容。
  • 未处理URL参数重复添加逻辑:直接拼接?source=,未检查原嵌入URL是否已存在查询参数或source参数,若脚本重复执行(如页面刷新、事件重复触发),会多次添加source参数,破坏URL格式。

修复方案

1. 修正变量作用域,正确获取source参数值

移除全局results变量,在$.urlParam函数内部处理结果,直接使用函数返回的实际参数值进行拼接。

2. 安全拼接URL参数

使用URL对象处理参数拼接,自动处理?和&的区分,同时覆盖已存在的source参数,避免重复添加。

修复后的完整代码

$(document).ready(function(){  
    // Step 1: 提取URL中的source参数
    $.urlParam = function(name){
        const results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);
        return results ? decodeURIComponent(results[1]) : '';
    };
    const sourceValue = $.urlParam('source');
    console.log(sourceValue);  
  
    // Step 2: 获取嵌入容器的原始URL
    const embedContainer = $(".qgiv-embed-container");
    const originalEmbedURL = embedContainer.attr("data-embed");
    console.log(originalEmbedURL);  
  
    // Step 3: 安全拼接source参数
    let finalURL;
    if (sourceValue) {
        // 使用URL对象自动处理参数逻辑,覆盖已存在的source参数
        const urlObj = new URL(originalEmbedURL);
        urlObj.searchParams.set('source', sourceValue);
        finalURL = urlObj.toString();
    } else {
        finalURL = originalEmbedURL;
    }
    console.log(finalURL);

    // 更新嵌入容器的data-embed属性
    embedContainer.attr("data-embed", finalURL);
});

关键改进点

  • 用局部变量替代全局变量,避免作用域污染;
  • 借助URL对象的searchParams方法,自动处理参数拼接规则,避免重复添加或格式错误;
  • 增加参数存在性判断,仅当source参数有效时才修改URL;
  • 明确更新data-embed属性,确保嵌入脚本使用修改后的URL。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:05:19