将params添加到现有URL

时间:2013-10-01 13:13:33

标签: javascript php

基于Adding a parameter to the URL with JavaScript我试图创建一个脚本,将参数添加到现有网址但有点失败,我不知道为什么......

    <script type="javascript">
    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('=');}
        //this will reload the page, it's likely better to store this until finished
        document.location.search = kvp.join('&'); 
    }
</script>
<label>
    <select name="id" onchange="window.location='somepage.php?page=inserari-note&selected_value='+this.value">
    <option>--Alege user--</option>
        <?php 
            while($runrows = mysql_fetch_assoc($run))
            {
                $user = $runrows ['user_login'];
                echo"<option value=\"$user\">$user</option>";
            }
        ?>
    </select>
</label>
<label>
    <select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">
    <option>--Alege Elev--</option>
        <?php 
            while($runrows4 = mysql_fetch_assoc($run4))
            {
                $elev = $runrows4 ['Nume'];
                echo"<option value=\"$elev\">$elev</option>";
            }
        ?>
    </select>
</label>

因此,第一个select正在为学生填充第二个select,并将网址更改为somepage.php?page=inserari-note&selected_value='+this.value哪个效果很好,但是当我点击第二个{{1}的选项时}, 什么都没发生。在我看来,它应该添加现有的URL,这是我之前提到的,值select,以便URL看起来像是&selected_valueelev="chosen-option"。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您应该通过以下方式定义脚本标记:

<script type="text/javascript">
...
</script>

此外,您还有以下语法错误:

// remove + before this.value    
<select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">