更改URL中参数的值

时间:2011-09-05 08:40:28

标签: javascript jquery url parameters

我正在尝试使用javascript函数来更改URL中参数的值,并在文本框中输入值,但没有运气。那是因为我注意到代码设计师而不是图表设计师。 这是我需要更改“城市”参数的网址:

http://server/ad_new_customer.php?&city=&uri=http://server/adauga_exp.php

我通过My​​SQL查询在输入文本框中生成数据,如下所示:

<input type='text' id='city' name='city' style="width:190px; align:left;" value="<?php echo $city; ?>" /> </td>
<script type="text/javascript">
//change the value of parameter in the URL function
function changeURI(key, value) {
var query = document.location.search.substring(1);
var query_q = query.split("?");
var vars = query_q[1].split("&");
for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == key) {
        vars[i] = pair[0] + "=" + value;
    }
}
return vars.join("&");
}
//jQuery making the auto-suggestion query for the input ID
$().ready(function() {
$("#city").autocomplete("core/exp_city.php", {
    width: 340,
    matchContains: true,
    selectFirst: false
}).return(changeURI("city", this.value}));
});
</script>

如何更改所选值的参数值? 请再次告诉一位谦逊的设计师。 谢谢!

L.E.

我做了一个解决方法,用这个改变了changeURI()函数:

function changeURI(key, value)
{
key = escape(key); value = escape(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('=');
    }else{
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&'); 
    }

}

在StackOverflow上找到并使用$ .result()函数从jQuery查询中调用它:

<script type="text/javascript">
$().ready(function() {
$("#city").autocomplete("core/exp_city.php", {
    width: 340,
    matchContains: true,
    selectFirst: false
}).result(function() {changeURI("city",this.value)});
});

</script>

2 个答案:

答案 0 :(得分:1)

你得到什么错误?你收到任何javascript错误?另外,尝试将代码更改为

之类的内容
url = url.replace(new RegExp("city=", 'g'), "city="+value).

此外,问题中写的网址在city参数之前不应为&,因为第一个参数以?开头,因此网址应为:

http://server/ad_new_customer.php?city=&uri=http://server/adauga_exp.php

检查这是否是问题。

答案 1 :(得分:0)

在您的示例中,document.location.search.substring(1)已经摆脱了问号:它应该返回&city=&uri=http://server/adauga_exp.php。然后对“?”进行拆分并尝试取第二个数组元素应返回undefined,因为不再有任何“?”字符。在那时直接跳到var vars = query.split("&"),剩下的看起来对我来说没问题。

相关问题