【问题标题】:change the value of parameter in URL更改 URL 中参数的值
【发布时间】:2011-09-05 08:40:28
【问题描述】:

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

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

我正在使用 jQuery 通过 MySQL 查询在输入文本框中生成数据,如下所示:

<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>

【问题讨论】:

    标签: javascript jquery url parameters


    【解决方案1】:

    您遇到了什么错误?你有任何 javascript 错误吗?另外,尝试将您的代码更改为类似

    url = url.replace(new RegExp("city=", 'g'), "city="+value).
    

    另外,问题中写的网址不应在城市参数之前有&amp;,因为第一个参数以?开头,所以网址应该是:

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

    检查是否是问题所在。

    【讨论】:

    • 嗨@Ankit,实际上它并没有给我任何错误,只是它没有进行所需的更改,我已将第一个参数修改为仅以“?”开头,但没有运气。我不知道如何实现 replace(new RegExp()) 并且我读到它比其他解决方案慢。谢谢。
    【解决方案2】:

    在您的示例中,document.location.search.substring(1) 已经去掉了问号:它应该返回 &amp;city=&amp;uri=http://server/adauga_exp.php。然后对“?”进行拆分并且尝试获取第二个数组元素应该返回未定义,因为不再有任何“?”人物。到那时直接跳到var vars = query.split("&amp;"),其余的我觉得还可以。

    【讨论】:

    • 谢谢@sthobrien,你说得对,我跳过了 query_q 变量,但仍然没有用。无论如何,我已经设法使用另一个 changeURI() 函数并且它确实有效。谢谢。
    猜你喜欢
    • 2013-05-11
    • 2021-05-27
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多