从JavaScript中的按钮在onclick window.location上添加php GET变量

时间:2019-10-27 13:05:02

标签: javascript

我有一个像这样的按钮:

<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 1</button>
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 2</button>

如何使用javascript代码将&VAR3=3添加到onclick中以使其具有

<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2&VAR3=3'">BUTTON 1</button>
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2&VAR3=3'">BUTTON 2</button>

2 个答案:

答案 0 :(得分:0)

假设用户正在浏览的当前URL是“ page_test.php?VAR=1&VAR2=2”,那么此代码会将&VAR3=3附加到URL:

HTML:

<button class="buttons" onclick="insertParam('VAR3', '3')">BUTTON 1</button>

JS:

function insertParam(key, value)
{
    key = encodeURI(key); 
    value = encodeURI(value);
    var kvp = document.location.search.substr(1).split('&');
    var i=kvp.length; 
    var x; 
    while(i--) 
    {
       x = kvp[i].split('=');
       if (x[0]==key)
       {
          x[1] = value;
          kvp[i] = x.join('=');
          break;
       }
    }

    if(i<0) 
    {
       kvp[kvp.length] = [key,value].join('=');
    }

    document.location.search = kvp.join('&'); 
}

答案 1 :(得分:0)

HTML:

就像Max Voisard一样,假设用户正在浏览的当前URL是"page_test.php?VAR=1&VAR2=2",我将尝试做些简单的事情。

<button class="buttons" onclick="insertParam('VAR3', '3')">BUTTON 1</button>

JS:

function insertParam(key, value)
{
  key   = encodeURI(key); 
  value = encodeURI(value);
  return window.location.href + `&${ key }=${ value }` 
}