对不起我的英语。我有以下javascript行用于重定向网页。
<script>
window.location.href = "https://www.example.com/example_0/" + document.location.search;
</script>
在以下条件下,我需要帮助使用window.location.href修改url。
让我更好地解释一下,原始url是这样构建的:
http://www.example.com/result.php?clientId=528873&lang=IT
我必须确保?clientId=参数在url中读取,并基于此参数通过此正确的窗口将用户重定向到正确的url。localion.href命令,例如,如果clientId为=a 849679,则返回this:
window.location.href = "https://www.example1.com/example_1/" + document.location.search;
而如果参数是818586,则通过该命令将用户重定向到正确的url
window.location.href = "https://www.example2.com/example_2/" + document.location.search;
等等。。。有人能帮我完整地写下正确的代码吗?我是一个压倒性的,我不知道该怎么做:-(
根据您的浏览器支持,您可以使用URLSearchParams。https://caniuse.com/#feat=urlsearchparams
const urlParams = new URLSearchParams(window.location.search);
const clientId = urlParams.get('clientId');
if(clientId === '849679') {
window.location.href = "https://www.example1.com/example_1/" + document.location.search;
} else if (clientId === '818586') {
window.location.href = "https://www.example2.com/example_2/" + document.location.search;
}
另一种解决方案是使用regexp或另一个库来提取查询参数。
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/+/g, ' '));
}
const clientId = getParameterByName('clientId');
if(clientId === '849679') {
window.location.href = "https://www.example1.com/example_1/" + document.location.search;
} else if (clientId === '818586') {
window.location.href = "https://www.example2.com/example_2/" + document.location.search;
}
谢谢你的好意,一切都很顺利。
我只想问你最后一件事,因为主网址是
http://www.example.com/result.php?clientId=528873&lang=IT
我想补充一下?a_aid=xxx之前?clientID=528873是否可以转换?clientID进入&重建url时的clientID?
也就是说,我想成为:
http://www.example.com/result.php?a_aid=xxx&客户端ID=528873&lang=IT