2011-05-22 41 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

答案是一個方法。另一種方法是添加一個名爲「價格」的隱藏字段,然後填寫它,然後將其提交給您想要的值。

相關問題