有些情況下,同一個form在不同的情況下送出到不同的處理動作,可以在js中動态改變form的屬性,滿足不同條件的form送出需求。
如:
<form id="form" name="form" method="POST" enctype="multipart/form-data" action="action1.jsp" target="iframe">
<input type="file" name="file" id="file" class="input_text80"></input>
<input id="name" name="name"/>
<input type="button" value="更新到探測點" onClick="javascript:formSubmit();"></input>
</form>
<iframe name="iframe"></iframe>
現在需要條件1的情況下按上面的方式送出,以method="POST" enctype="multipart/form-data" action="action1.jsp" target="iframe"送出到action1.jsp進行處理;條件2的情況下需要按照普通文本方式送出到action2.jsp處理,并打開新頁面。則需要通過js的方式動态改變form的屬性:
function formSubmit(){
if(flag=="1"){
$("#form").submit();
}else if(flag=="2"){
$("#form").attr("action","deployResult.jsp");
$("#form").attr("target","_blank");
$("#form").attr("method","GET");
$("#form").attr("enctype","application/x-www-form-urlencoded");
$("#form").attr("encoding","application/x-www-form-urlencoded");
$("#form").submit();
}
}
注:
改變form的enctype屬性時,如果隻寫$("#form").attr("enctype","application/x-www-form-urlencoded");
将不起作用,必須将以下兩句結合才能生效:
$("#form").attr("enctype","application/x-www-form-urlencoded");
$("#form").attr("encoding","application/x-www-form-urlencoded");
其中,enctype的屬性值含義參考博文《HTML <form> 标簽的 enctype 屬性》