2014-03-24 80 views
3

我有兩個html表單,我將一個html表單的輸入數據發佈到另一個html form.I想要檢索使用表單2上的表單1發佈的變量的值。如何使用javascript從張貼的html表單中獲取值

<form name ="form1" id ="form1" method ="post" action = "form2.html> 
    <input id ="sendToForm2" type ="hidden" value ="send this to form2"/> 
</form> 

我的問題是,一旦它從形式發佈1使用JavaScript來形成2如何獲得隱藏變量sendToForm2對形式2的值。

+0

你需要使用類似PHP的東西,我猜這個。 – user3004356

+0

創建一個小提琴。 –

+0

其簡單的html和javscript。我不知道關於PHP。 –

回答

2

不能使用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您可以使用此功能(從this post上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>