Javascript url.location&换成?

时间:2016-06-02 08:23:56

标签: javascript jquery

我的html页面中有一个语言选择单选按钮,在选择一种语言时,我会调用相同的网址来追加'?lang ='。这是我通过js做的,当提交网址时,&被替换为?下面是我的js代码。

SELECT *
FROM tbla
ORDER BY 
    CASE WHEN curr >= DATE '2016-06-02' THEN curr END,
    CASE WHEN active THEN curr END DESC NULLS LAST,
    curr DESC;

现在,当我选择语言时,浏览器中的网址为http://localhost:8080/test/report.htm?count=40&name=jerry?lang=en。我调试了代码,看到网址为http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en,但是在提交时会发生变化。

1 个答案:

答案 0 :(得分:-1)

您的代码似乎没问题。你应该考虑使用函数,它们使调试变得更容易。

function removeBookmarkFromUrl(url) {
    var arr = url.split("#");
    return arr[0];
}

function getLangUrl(url, lang){
  url = removeBookmarkFromUrl(url);
  if (url.indexOf('?lang') >= 0 || url.indexOf('&lang') >= 0) {
      var pos = (url.indexOf('?lang') >=0 ) ? url.indexOf('?lang') : url.indexOf('&lang');
      var currentLang = url.slice(pos + 6, pos + 8);
      if (url.charAt(pos) == '?') {
        url = url.replace('?lang=' + currentLang, '?lang=' + lang);
        return url;
      }
      else if (url.charAt(pos) == '&') {
         url = url.replace('&lang=' + currentLang, '&lang=' + lang);
         return url;
      }
  } else {
      if (url.indexOf('?') >= 0) {
        return url + '&lang=' + lang;
      } else {
         return url + '?lang=' + lang;
      }
   }
}

var url;
url = "http://localhost:8080/test/report.htm";
console.log(url, " \n-> ", getLangUrl(url, 'de'));

url = "http://localhost:8080/test/report.htm?lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));

url = "http://localhost:8080/test/report.htm?count=40&name=jerry";
console.log(url, " \n-> ", getLangUrl(url, 'de'));

url = "http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));