我正在构建一个使用许多过滤器的搜索功能。我决定使用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" />
提前谢谢
ruven
答案 0 :(得分:1)
这个(working demo):
<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>