2

我正在构建一个使用许多过滤器的搜索功能。我决定使用 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 教授。所以我需要一点帮助。

我能做什么,所以我得到一个查询字符串,如下所示:

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

HTML 是“普通”输入字段

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

先感谢您

鲁文

4

1 回答 1

1

这个怎么样(工作演示):

<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>
于 2012-12-29T13:32:23.613 回答