我对我的英语感到抱歉。 我有以下用于重定向网页的 javascript 行。
<script>
window.location.href = "https://www.example.com/example_0/" + document.location.search;
</script>
我需要帮助在以下条件下使用 window.location.href 修改 url。
让我更好地解释一下,原始网址是这样构建的:
http://www.example.com/result.php?clientId=528873&lang=IT
我必须确保在 url 中读取 ?clientId= 参数,并根据此参数通过正确的 window.location.href 命令将用户重定向到正确的 url,例如,如果 clientID = a 849679返回此:
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;
}
关于javascript - 如何使用参数编写条件window.location.href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58575121/