缩短查询字符串用于搜索和许多过滤器



我正在构建一个使用许多过滤器的搜索函数。我决定使用get方法而不是post(不同的原因)。问题是,当使用许多过滤器时,查询字符串变得很长,特别是当我使用同名过滤器时,所以我得到

myurl.com?filter1[]=val1&filter1[]=val2&filter2=val

为了更好地控制和防止0值,我尝试serializeArray:

var array = {}; 
jQuery.each(jQuery('form').serializeArray(), function(index,val) {
if (val.value != 0 )
    array[value.name] = val.value;
});

但是通过这种方式,它用filter1的最后一个值覆盖了第一个filter1,因此多个值不起作用。然后我有"问题"来创建查询字符串。我不是一个javascript教授,所以我需要一点帮助在这里。

我能做什么,所以我得到一个querystring看起来像:

myurl.com?filter1=val1|val2&filter2=val and so on

HTML是"正常"的输入字段

<input type="checkbox" name="filter1[]" />
<input type="text" name="filter2" />

提前谢谢你

路文

这个如何(工作演示):

<form action="search.html">
    <input type="text" value="val1" name="filter1" />
    <input type="text" value="val2" name="filter1" />
    <input type="text" value="val" name="filter2" />
    <input type="submit" value="search" name="cmdSearch" />
</form>
​
<script>
    // don't do anything until document is ready
    $(function() {
        // register to form submit event
        $('form').submit(function(e){
            // stop the form from doing its default action (submit-GET)
            e.preventDefault();
            // initialise url
            var url = '';
            // keep track of previously enumerated field
            var prev = '';      
            // iterate all fields in the form except the submit button(s)
            $('input:not([type="submit"])', $(this)).each(function(){
                // get the name of this field, with null coalesce
                var name = $(this).attr('name') || '';
                // get the value of this field
                var val = $(this).attr('value');
                // does this field have the same name as the previous?
                if (name.toLowerCase() == prev.toLowerCase()) {
                    // same name therefore we have already appended the name
                    // append value separator
                    url += '|';
                }
                else {
                    // different name, track new name
                    prev = name;
                    // append parameter separator, parameter name, equals char
                    url += '&' + name + '=';
                }
                // append value of this field         
                url += val;
            });
            // removing leading ampersand
            if (url.length && [0] == '&') {
                url = url.substring(1);            
            }       
            // insert leading question mark
            url = '?' + url;
            // insert url from "action" attribute of the form
            url = $(this).attr('action') + url;
            // display url (delete this line)
            alert(url);
            // redirect to the new url (simulates the GET)
            window.location.href = url;
        });
    });
</script>

最新更新