首页 > 解决方案 > 为什么我要检索的 URL 参数没有完全显示?

问题描述

我正在使用“posName”参数跟踪 URL,例如:

example.com?posName=内容+&+社区+经理+(H/F)

但我的代码只返回“内容”

function () {
    var uri = document.location.href;
    var uri_dec = decodeURIComponent(uri);
    var url = new URL(uri_dec);
    var posName= url.searchParams.get("posName");
    return posName;
}

我怎样才能得到完整的参数?

编辑: 我有另一个网址,如:

example.com?posName= Club+&+Animator+(H/F)

并且代码返回完整的参数......那么是导致这个问题的参数的长度吗?

标签: javascripturl-parameters

解决方案


我已修改您的函数以接受 URI 作为参数。您需要在将参数附加到查询字符串之前对其进行编码(我们在这里看不到此代码)。函数中的 decodeURIComponent 也不是必需的。

function getPosName (URI) {
    //var uri_dec = decodeURIComponent(uri);
    var url = new URL(URI);
    var posName = url.searchParams.get("posName");
  return posName;
}

console.log("Using your current URI:", getPosName("http://exemple.com?posName=Content+&+Community+Manager+(H/F)"))

const encodedParam = encodeURIComponent("Content & Community Manager (H/F)")
console.log("Encoded Parameter:", encodedParam)
const wellFormedURI = `http://exemple.com?posName=${encodedParam}`
console.log("Well Formed URI:", wellFormedURI)
console.log("Using well formed URI:", getPosName(wellFormedURI))


推荐阅读