表單使用get提交,問號傳值問題

最近換工作,從以前做中間件服務器換到了移動互聯網的app服務端開發,也就又重新使用一些開源框架和JavaScript等技術,以前工作都是使用原始JavaScript,自己封裝函數,自己寫代碼來實現功能,現在項目中在使用jQuery框架,突然發現jQuery使用起來好方便啊。
今天在寫代碼過程中發現項目的一個bug,項目中使用jQuery進行表單提交,使用get方式提交,想在action的url中通過問好?來攜帶get參數,代碼入下:
var url = "${pageContext.request.contextPath}/Project/path?"+"tel="+""+"&startTime="+startTime+"&endTime="+endTime;
$("form").attr("action",url);
$("form").attr("method","get");
$("form").submit();

但是在後臺,通過request.getParameter(“startTime”)來取值時,卻一直取不到值,上網查看發現:HTML規定,通過GET方法提交表單時,action地址裏的query串會被丟棄。原文如下:
HTML 4.0.1(http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.4
If the method is “get” and the action is an HTTP URI, the user agent
takes the value of action, appends a `?’ to it, then appends the form
data set, encoded using the “application/x-www-form-urlencoded”
content type.
HTML 5(http://www.w3.org/TR/2011/WD-html5-20110525/association-of-controls-and-forms.html#form-submission-algorithm
Mutate action URL
Let query be the result of encoding the form data
set using the application/x-www-form-urlencoded encoding algorithm,
interpreted as a US-ASCII string.
Let destination be a new URL that is equal to the action except that
its component is replaced by query (adding a U+003F QUESTION
MARK character (?) if appropriate).
因此如果要實現該功能,則不能使用問號在url中攜帶參數,可以在表單中使用隱藏域,即hidden來隱藏,再使用jQuery來賦值,後提交,使用post提交方式即可。或者也可以使用js,在獲取form後使用append來追加隱藏域,這樣也可以把值傳過去。當然也許還有更好的方法,本人試過第一種,沒有問題。
在此可以看出,其實很多細節的東西會被我們忽略掉,尤其是在做js相關的東西,零碎的東西太多,一定要注意細節,在這些方面,細節決定成敗。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章