在 Web 開發中,表單提交是常見操作。若希望以非同步方式送出資料,通常會使用 AJAX;若希望模擬表單提交,也可以使用傳統 form 或建立虛擬表單。
第一種方式是透過 XMLHttpRequest 建立 POST 請求。這種方式可以自訂請求標頭與傳送內容。
var xmlobj;
function CreateXMLHttpRequest() {
if (window.ActiveXObject) {
try {
xmlobj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlobj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlobj = false;
}
}
} else if (window.XMLHttpRequest) {
xmlobj = new XMLHttpRequest();
}
}
function SubmitArticle(act, cityname, antique) {
CreateXMLHttpRequest();
var parm = "act=" + act + "&cityname=" + cityname + "&antique=" + antique;
xmlobj.open("POST", "/weather/include/weather.php", true);
xmlobj.setRequestHeader("cache-control", "no-cache");
xmlobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xmlobj.onreadystatechange = StatHandler;
xmlobj.send(parm);
}
第二種方式是動態建立一個隱藏的 form,將參數塞入表單元素中,再呼叫 submit() 送出。
function post(URL, PARAMS) {
var temp = document.createElement("form");
temp.action = URL;
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = PARAMS[x];
temp.appendChild(opt);
}
document.body.appendChild(temp);
temp.submit();
return temp;
}
呼叫方式如下:
post("pages/statisticsJsp/excel.action", {
html: prnhtml,
cm1: "sdsddsd",
cm2: "haha"
});
根據實際需求選擇合適的方式,才能讓 POST 提交更穩定且易於維護。