jQuery 如何使用jquery来操作查询字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2053157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:39:39  来源:igfitidea点击:

How to use jquery to manipulate the querystring

jqueryurlquery-string

提问by CoffeeMonster

I have a select dropdown with id's mapped to values. On the onChange event I want to redirect to the same url but with 'id=value' appended to the querystring.

我有一个选择下拉列表,其中 id 映射到值。在 onChange 事件中,我想重定向到相同的 url,但将 'id=value' 附加到查询字符串。

How do I check that this 'id' option isn't already in the querystring (I don't want multiple values) and replace / append as necessary.

我如何检查这个“id”选项是否已经在查询字符串中(我不想要多个值)并根据需要替换/追加。

How do I check if '?' is already in the querystring and append to the url if its not.

我如何检查“?” 已经在查询字符串中,如果不是,则附加到 url。

Is there an easy way with jquery to do this?

jquery 有没有一种简单的方法可以做到这一点?

It must do something similar under the hood for $().ajax(url, {options})calls. I was hoping I could just do $().redirect( url, { id : $(this).val() })or somesuch.

它必须在后台为$().ajax(url, {options})调用做类似的事情。我希望我能做些$().redirect( url, { id : $(this).val() })什么。

Thanks in advance.

提前致谢。

Note: This page may or may not have a few different query options passed in (which set defaults on other form options) so replacing the whole querystring is not an option.

注意:此页面可能会或可能不会传入一些不同的查询选项(在其他表单选项上设置默认值),因此替换整个查询字符串不是一个选项。

<html>
<head><script type="text/javascript" src="/jquery-1.3.2.min.js"></script></head>
<body>
  <script>
    $(function(){                                                                                                                                         
        $('#selector').change(function(){                                                                                                                 
            // problem if 'id' option already exists
            var url = location.href + '?;id=' + $(this).val();                                                                                            
            location.assign( url );
        });                                                                                                                                               
    });                                                                                                                                                   
  </script>

  <a href="#" onclick="location.assign( location.pathname )">reset</a>                                                                                      
  <form>                                                                                                                                                    
    <select id='selector' name='id'>                                                                                                                      
        <option value='1'>one</option>                                                                                                                    
        <option value='2'>two</option>                                                                                                                    
        <option value='3'>three</option>                                                                                                                  
    </select>                                                                                                                                             
  </form>
</body>
</html>

回答by CoffeeMonster

I ended up going with a RegExp match to override the options. jQuery.param takes a hash and serialises it to a query_string but it doesn't provide the inverse (breaking up a query_string).

我最终使用 RegExp 匹配来覆盖选项。jQuery.param 接受一个散列并将其序列化为一个 query_string 但它不提供反向(分解一个 query_string)。

// put function into jQuery namespace
jQuery.redirect = function(url, params) {

    url = url || window.location.href || '';
    url =  url.match(/\?/) ? url : url + '?';

    for ( var key in params ) {
        var re = RegExp( ';?' + key + '=?[^&;]*', 'g' );
        url = url.replace( re, '');
        url += ';' + key + '=' + params[key]; 
    }  
    // cleanup url 
    url = url.replace(/[;&]$/, '');
    url = url.replace(/\?[;&]/, '?'); 
    url = url.replace(/[;&]{2}/g, ';');
    // $(location).attr('href', url);
    window.location.replace( url ); 
};

Then in the html

然后在html中

$('#selector').change(function(){ 
   $.redirect( location.href, { id : $(this).val() })
})

Thanks to everyone that responded.

感谢所有回复的人。

回答by Benkinass

Based on CoffeeMonster's answer:

基于 CoffeeMonster 的回答:

There is a problem when the location.href contains a hash part:

www.example.com#hashbecomes www.example.com#hash?id=whateverwhich results in ?id=whatevernot being interpreted by the server.

location.href 包含哈希部分时会出现问题:

www.example.com#hash变成www.example.com#hash?id=whatever导致?id=whatever服务器无法解释的问题。

Fixed it by removing the hash part of the url: url.split("#")[0];

通过删除 url 的哈希部分来修复它: url.split("#")[0];

// put function into jQuery namespace
jQuery.redirect = function(url, params) {

    url = url || window.location.href || '';
    url = url.split("#")[0];
    url =  url.match(/\?/) ? url : url + '?';

    for ( var key in params ) {
        var re = RegExp( ';?' + key + '=?[^&;]*', 'g' );
        url = url.replace( re, '');
        url += ';' + key + '=' + params[key]; 
    }  
    // cleanup url 
    url = url.replace(/[;&]$/, '');
    url = url.replace(/\?[;&]/, '?'); 
    url = url.replace(/[;&]{2}/g, ';');
    // $(location).attr('href', url);
    window.location.replace( url ); 
};

Now www.example.com#hashbecomes www.example.com?id=whatever

现在www.example.com#hash变成www.example.com?id=whatever

回答by Alpha Codemonkey

setting window.location.searchwill update the url's query string (and overwrite a value if it already exits)

设置window.location.search将更新 url 的查询字符串(如果它已经存在,则覆盖一个值)

$('#selector').change(function(){  
  window.location.search = "id=" + $(this).val();
}); 

回答by Jacob Relkin

This works like a charm:

这就像一个魅力:

jQuery.redirect = function( url ) {
   window.location.replace( url );  
};
$( "#selector" ).change( function() {
    var href = window.location.href.substring( 0, window.location.href.indexOf( '?' ) );
    $.redirect( href + '?id=' + $( this ).val() );
} );

回答by Danny Roberts

Try using the split function:

尝试使用 split 函数:

var url = location.href.split('?')[0] + '?;id=' + $(this).val();

splitreturns a list made up of the string split up by the string (like '?'), with that string removed.

split返回由字符串拆分的字符串组成的列表(如“?”),并删除该字符串。

回答by Grimace of Despair

I suspect the alleged solution is not working with specific variable names. Especially the line:

我怀疑所谓的解决方案不适用于特定的变量名称。特别是这条线:

RegExp( ';?' + key + '=?[^&;]*', 'g' )

If key is a character sequence present elsewhere within the querystring, that occurrence will be mistakenly replaced also (try one letter, e.g. 'a'). This is because the regex leaves the string boundaries open (leading ';' and trailing '=' are both optional). Maybe the epxression better be something like:

如果 key 是查询字符串中其他地方出现的字符序列,则该出现的字符也会被错误地替换(尝试使用一个字母,例如 'a')。这是因为正则表达式使字符串边界保持开放(前导 ';' 和尾随 '=' 都是可选的)。也许epxression最好是这样的:

RegExp( '[;&]' + key + '=?[^&;]*', 'g' )

Though I haven't tested it yet.

虽然我还没有测试过。