Javascript建立虛擬form提交表單資訊
阿新 • • 發佈:2019-01-03
今天遇到了這樣一個問題:在form複選框的表單,有一元件需要使用ajax的post操作來進行動態資料庫更新,那麼在form表單中就有兩個post的操作,當我每次執行ajax的時候,會自動提交form表單的內容,這不是我想要的。
解決方案:更換個思路,通過js獲取到input的內容,然後根據js獲取的內容使用js建立一個虛擬的form進行提交。
程式碼如下:
$(document).ready(function(){
$('#pintu_btn').click(function() {
var temp = document.createElement("form" );//建立form標籤
temp.action =;//這裡寫URL
temp.method = "post";//post方式提交
temp.style.display = "none";//設定為不可見
obj = document.getElementsByName("pintubox[]");//獲取源form標籤的內容
pintubox = [];
for(k in obj){
if(obj[k].checked){;
//建立input標籤並設定相關引數
var inputTemp = document.createElement("input");
inputTemp.setAttribute("type", "checkbox");
inputTemp.setAttribute("name", "pintubox[]");
inputTemp.setAttribute("value", obj[k].value);
inputTemp.setAttribute("checked" ,"checked");
temp.appendChild(inputTemp);//把input標籤新增到form標籤內
}
}
document.body.appendChild(temp);//將form標籤新增到body標籤內
temp.submit();//提交form
});
});