如何更改已提交表单的查询字符串
How change the querystring for a submited form
我有一个包含许多下拉列表的表单,我想在提交表单时排除 none 个选定的列表,使其不出现在查询字符串中。
那么我可以使用一些模块或过滤器来改变这种行为吗?
例如:
当我搜索测试时,url 将是
/someaction?q=test&select1=&select2=
所需的 url 是:
/someaction?q=测试
<form action="/search" action="Get">
<label>Search term <input name="q"></label>
<select id="select1" name="select1">
<option value="1">option 1</option>
</select>
<select id="select2" name="select2">
<option value="1">option 1</option>
</select>
<input type="submit">
</form>
由于您使用 GET 方法进行表单操作,您可以处理提交事件以防止正常提交,并使用带正则表达式的 replace()
函数去除空值,然后使用 location.href
重定向到目标 URL:
$('form').submit(function (e) {
e.preventDefault();
var queryString = $(this).serialize().replace(/&?[\w\-\d_]+=&|&?[\w\-\d_]+=$/gi, "");
url = this.getAttribute('action') + (queryString.length > 0 ? "?" + queryString : "");
// returns URL /search?q=something when both select elements are empty
location.href = url;
});
或者使用 attr()
或 prop()
禁用没有值的 select
元素,以防止它们在查询字符串中使用,使用正常表单提交事件:
$('form').submit(function () {
$('select').each(function () {
if ($(this).val() == '') {
$(this).prop('disabled', 'disabled'); // or prop('disabled', true)
});
});
我有一个包含许多下拉列表的表单,我想在提交表单时排除 none 个选定的列表,使其不出现在查询字符串中。 那么我可以使用一些模块或过滤器来改变这种行为吗?
例如: 当我搜索测试时,url 将是 /someaction?q=test&select1=&select2= 所需的 url 是: /someaction?q=测试
<form action="/search" action="Get">
<label>Search term <input name="q"></label>
<select id="select1" name="select1">
<option value="1">option 1</option>
</select>
<select id="select2" name="select2">
<option value="1">option 1</option>
</select>
<input type="submit">
</form>
由于您使用 GET 方法进行表单操作,您可以处理提交事件以防止正常提交,并使用带正则表达式的 replace()
函数去除空值,然后使用 location.href
重定向到目标 URL:
$('form').submit(function (e) {
e.preventDefault();
var queryString = $(this).serialize().replace(/&?[\w\-\d_]+=&|&?[\w\-\d_]+=$/gi, "");
url = this.getAttribute('action') + (queryString.length > 0 ? "?" + queryString : "");
// returns URL /search?q=something when both select elements are empty
location.href = url;
});
或者使用 attr()
或 prop()
禁用没有值的 select
元素,以防止它们在查询字符串中使用,使用正常表单提交事件:
$('form').submit(function () {
$('select').each(function () {
if ($(this).val() == '') {
$(this).prop('disabled', 'disabled'); // or prop('disabled', true)
});
});