[英]How to get values from posted html form using javascript
我有兩個html表單,我將輸入數據從一個html表單發布到另一個html表單。我想檢索在表單2上使用表單1發布的變量值。
<form name ="form1" id ="form1" method ="post" action = "form2.html>
<input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>
我的問題是,一旦使用javascript從表單1發布到表單2,如何在表單2上獲取隱藏變量sendToForm2的值。
您不能使用POST
方法,因為對於純 HTML頁面,您沒有HTTP標頭,但HTML頁面代碼本身和URL(帶有查詢字符串)。
你可以做的是使用GET
而不是POST
然后解析查詢字符串來提取它們:
<form name ="form1" id ="form1" method ="GET" action = "form2.html>
<input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>
然后在你的form2.html
你可以使用這個函數(從SO上的這篇文章 )來解析查詢字符串:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
現在(讓我使用jQuery)您可以使用以下方法訪問它們:
<form ...>
<input id ="sentFromForm1" type ="hidden" value =""/>
</form>
</script>
$("#sentFromForm1").val(getParameterByName("sendToForm2"));
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.