gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:52:07 25 4
gpt4 key购买 nike

我正在构建一个使用许多过滤器的搜索功能。我决定使用 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" />

提前致谢

鲁文

最佳答案

这个怎么样(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>

关于javascript - 缩短用于搜索和许多过滤器的查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14081991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com