如何使用javascript
问题描述:
我开发了一个网站,在两种语言工作,我改变语言代码的网址,我需要改变URL包括选定URL 我究竟需要的是如何使用javascript
1-选择当前网址
2-检查它是否包含任何语言代码
3-追加的代码是否存在,如果不存在,或者改变代码到所选择的一个
例如:
http://localhost:11767/Home/resultMain?model=1&&type=1
上面的链接工作与英语,因为它是ES语言的默认,当用户点击它应该是
http://localhost:11767/es/Home/resultMain?model=1&&type=1
答
您可以分析与一个元素的帮助下,URL然后更换你想要的部分,并重新建立的网址:
function addReplaceLangCode(url, langCode) {
var a = document.createElement('a');
a.href = document.getElementById('url').value; // or document.location.href;
var paths = a.pathname.split('/');
paths.shift();
if(paths[0].length == 2) {
paths[0] = langCode;
}else{
paths.unshift(langCode);
}
return a.protocol + '//' +
a.host + '/' + paths.join('/') +
(a.search != '' ? a.search : '') +
(a.hash != '' ? a.hash : '');
}
function onClickReplace() {
document.getElementById('result').innerHTML = addReplaceLangCode(document.location.href, 'es');
}
URL : <input type="text" id="url" style="width:400px" value="http://localhost:11767/Home/resultMain?model=1&&type=1"><input type="button" value="Replace" onclick="onClickReplace()"><br />
Result: <span id="result"></span>
答
我不知道这是否正是这一点,你想要什么。但JavaScript可以使用对象“位置”获取URL。特别是location.pathname
对你很有用。您可以在location.pathname
上应用reg-exp来检查URL是否包含/es/
,如果是,则通过适当的Ajax请求将网站翻译成您的后端。
但通常我建议使用后端路由。我认为最好的解决方案 - 使用http标头通知服务器关于首选语言。
https://www.w3.org/International/questions/qa-accept-lang-locales
答
根据上面的@Bulnet Vural的回答,我写了下面的代码,因为我需要切换la nguage路径进出网址。
var getOtherLanguageLocation = function (currentUrl, languagePath) {
// based on https://*.com/a/42176588/1378980
var anchorTag = document.createElement('a');
anchorTag.href = currentUrl;
var paths = anchorTag.pathname.split("/");
// remove all the empty items so we don't get double slash when joining later.
var paths = paths.filter(function (e) { return e !== '' })
// the language will be at index 1 of the paths
if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
// remove the language prefix
paths.splice(0, 1);
} else {
// add the language prefix
paths.unshift(languagePath);
}
return anchorTag.protocol + '//' +
anchorTag.host + '/' + paths.join('/') +
anchorTag.search + anchorTag.hash;
};
你的后端是用哪种语言编写的?你在使用节点js吗? – Daniel
@Daniel ASP.NET MVC – Moustafa
更改window.location? –