2011-05-22 40 views
5

假设我有我的网页一个简单的形式是这样的:如何使用JQuery提交我的GET表单时更改查询字符串?

<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> 

当我提交我的形式,我有以下网址:

http://.../properties/search?min_price=100000&max_price=200000

我想改变这个网址有:

http://.../properties/search?price=100000,200000

为了做到这一点,我使用jQuery和JQuery querystring plugin

$(document).ready(function() { 
    $("#form_search").submit(function() { 
     var querystring = rewrite_interval_qstring(); 
     // querystring equals "?price=100000,200000" -> exactly what I want ! 

     // ??? 
    }); 
}); 

如何更改(评论“???”)提交网址?我已经单独测试了以下说明,但不起作用。

window.location = querystring; 
window.location.href = querystring; 
window.location.search = querystring; 

回答

2

您需要防止默认提交操作的发生

$(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. 
    }); 
}); 
6

你快到了。拦截提交事件(如你正在做的),提取最小值和最大值,打造您的网址,并设置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; 
    }); 
}); 
1

答案是一个方法。另一种方法是添加一个名为“价格”的隐藏字段,然后填写它,然后将其提交给您想要的值。

相关问题