繁体   English   中英

jquery修改url获取参数

[英]jquery modify url get parameters

我有一个像这样的URL:

http://google.de/test.php?a=b&c=d&e=f

我知道只需修改一个GET参数:( c是“h”而不是“d”)

http://google.de/test.php?a=b&c=h&e=f

并重定向到新网址。 所有其他GET参数应该保持不变。

我怎么会这样做?

我同意最好在其他答案中提到为此目的使用库。

但是,如果您需要更简单的快速修复,这里是基于正则表达式的字符串替换解决方案。

var url = "http://my.com/page?x=y&z=1&w=34";

var regEx = /([?&]z)=([^#&]*)/g;
var newurl = url.replace(regEx, '$1=newValue');

这里我用'newVlaue'替换查询字符串键'z'

看看这个小提琴: http//jsfiddle.net/BuddhiP/PkNsx

如上所述window.location.search会给你带有查询字符串? 包括在内。

然后我将这些变成一个对象(可能有一个像http://github.com/medialize/URI.js这样的库),以便更容易使用params。 var params = { key: value, key1: value1}

然后,您可以修改所需的值,并将键值对转换回查询字符串。

在此之后,您可以使用window.location将用户移动到下一页。

PHP的一个鲜为人知的特性是现有参数的后一个命名会覆盖之前的参数。

掌握了这些知识,您可以执行以下操作:

location.href = location.href + '&c=h';

简单。

我已经整理了一个非常简单的方法,但它只适用于你想要实现的目标:

var url = 'http://google.de/test.php?a=b&c=d&e=f';
var gets =  url.split('.php?');
var ge = gets[1].split('&');
var change = ge[1].split('=');
var change[1] = 'h';
var newUrl = url[0] + '.php?' + ge[0] + '&' + change[0] + '=' + change[1] + '&' + ge[2];

你可以尝试这样的事情:

var changed = "h"; // you can vary this GET parameter

var url = "http://google.de/test.php?a=b&e=f&c=" + changed; // append it to the end

window.location = newurl; // redirect the user to the url

因为您的参数可以在任何地方。 所以这将工作正常

url="http://google.de/test.php?a=b&c=d&e=f";
url=url.replace(/&c=.*&/,"&c=h&")

设置或更新URL / QueryString参数,并使用HTML history.replaceState()更新URL

你可以尝试这样的事情:

var updateQueryStringParam = function (key, value) {
    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        keyRegex = new RegExp('([\?&])' + key + '[^&]*');

        // If param exists already, update it
        if (urlQueryString.match(keyRegex) !== null) {
            params = urlQueryString.replace(keyRegex, "$1" + newParam);
        } else { // Otherwise, add it to end of query string
            params = urlQueryString + '&' + newParam;
        }
    }
    window.history.replaceState({}, "", baseUrl + params);
};

 location.href = location.origin+location.pathname+location.search; 

用你的新参数替换location.search,例如“?foo = bar&tic = tac”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM