javascript 使用 JQuery 提交 GET 表单时如何更改查询字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6087634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the querystring when I submit my GET form using JQuery?
提问by Sandro Munda
Suppose that I have a simple form in my page like this :
假设我的页面中有一个简单的表单,如下所示:
<form action="/properties/search" method="GET" id="form_search">
<p>
<label for="price">Min price:</label>
<input type="text" name="min_price" id="min_price">
</p>
<p>
<label for="price">Max price:</label>
<input type="text" name="max_price" id="max_price">
</p>
<p>
<input type="submit">
</p>
</form>
When I submit my form, I have the following url :
当我提交表单时,我有以下网址:
http://.../properties/search?min_price=100000&max_price=200000
http://.../properties/search?min_price=100000&max_price=200000
I want to change this url to have :
我想将此网址更改为:
http://.../properties/search?price=100000,200000
http://.../properties/search?price=100000,200000
To do that, I'm using JQuery and the JQuery querystring plugin:
为此,我使用 JQuery 和JQuery 查询字符串插件:
$(document).ready(function() {
$("#form_search").submit(function() {
var querystring = rewrite_interval_qstring();
// querystring equals "?price=100000,200000" -> exactly what I want !
// ???
});
});
How can I change (comment "???") the submit url ? I have tested the following instructions separately, but it does not work.
如何更改(评论“???”)提交网址?我已经分别测试了以下说明,但它不起作用。
window.location = querystring;
window.location.href = querystring;
window.location.search = querystring;
采纳答案by Gary Green
You need to prevent the default submit action from happening
您需要防止默认提交操作发生
$(document).ready(function() {
$("#form_search").submit(function(event) {
event.preventDefault(); // <-- add this
var querystring = rewrite_interval_qstring();
// querystring equals "?price=100000,200000" -> exactly what I want !
window.location.href = querystring; // <-- this should work.
});
});
回答by Rob Cowie
You're almost there. Intercept the submit event (as you are doing), extract the min and max values, build your url and set window.location.href
你快到了。拦截提交事件(正如你所做的那样),提取最小值和最大值,构建你的 url 并设置 window.location.href
$(document).ready(function() {
$("#form_search").submit(function(event) {
event.preventDefault();
$this = $(this);
// var url = rewrite_interval_qstring();
var min_price = $('#min_price').val();
var max_price = $('#max_price').val();
var url = $this.attr('action') + '?price=' + min_price + ',' + max_price;
window.location.href = url;
});
});
回答by jerone
Answer by Rob Cowie is one method. Another one is adding a hidden field named "price" and fill it before submitting it with the value you want.
Rob Cowie 的回答是一种方法。另一种方法是添加一个名为“price”的隐藏字段,并在使用您想要的值提交之前填充它。