javascript - 在 URL 中添加一个变量而不是替换一个
问题描述
我遇到了一个 javascript 脚本的小问题。我正在尝试使我的网站多语言。全部设置在数据库中,我的选择适用于 URL 没有变量的页面。这是我的脚本:
<script type="text/javascript">
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
在主页的情况下,它可以工作,并http://localhost/
通过http://localhost/?lang=en
但是当我有一个已经设置变量的 URL 时,它会替换它。从http://localhost/modules/product/product.php?id=1
我有http://localhost/modules/product/product.php?lang=en
,我想要的结果是:
http://localhost/modules/product/product.php?id=1&lang=en
如何修复脚本以使其在两种情况下都能正常工作,或者添加变量,或者将它与现有的绑定?
解决方案
尝试检查 URL 中是否已存在查询字符串参数。
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
if (window.location.href.indexOf('?') >= 0) {
// There are already querystring params in the URL. Append my new param.
window.location.href = window.location.href + '&lang=' + thelang;
} else {
// There are not querystring params in the URL. Create my new param.
window.location.href = window.location.href + '?lang=' + thelang;
}
}
更新:说明后续的语言变化
这假定 lang 值将始终是两个字符。
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
var newUrl = window.location.href;
var langIndex = newUrl.indexOf('lang=');
if (langIndex >= 0) {
// Lang is already in the querystring params. Remove it.
newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
}
// Remove the final '?' or '&' character if there are no params remaining.
newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;
newUrl = newUrl.indexOf('?') >= 0
? newUrl + '&lang=' + thelang // There are already querystring params in the URL. Append my new param.
: newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.
window.location.href = newUrl;
}
推荐阅读
- node.js - IIOT OPCUA 警报和事件节点-红色
- java - 如何使用硒单击具有动态输入的单选按钮?
- python - 在 django 中上传文件后将待处理状态更改为已提交
- node.js - 防止外部用户连接websocket(wss)
- heroku - 在 Heroku 中部署同步融合示例
- amazon-web-services - 错误:MalformedCertificate:无法解析证书。请确保证书为 PEM 格式
- c# - System.Timer 奇怪的行为
- python - Python独立计算列表中的元素列表?
- python - 使用递归查找数的阶乘的 Python 程序
- python - 可以根据唯一值在数据框中删除行吗?