DIV CSS 佈局教程網

JavaScript 使用 POST 提交的兩種方式
編輯:關於JavaScript     

POST 提交的需求

在 Web 開發中,表單提交是常見操作。若希望以非同步方式送出資料,通常會使用 AJAX;若希望模擬表單提交,也可以使用傳統 form 或建立虛擬表單。

方式一:使用 XMLHttpRequest

第一種方式是透過 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"
});

兩種方式的比較

  • XMLHttpRequest 更適合需要自訂請求標頭與非同步處理的情境。
  • 虛擬表單更適合需要觸發瀏覽器原生表單提交行為的情境。

根據實際需求選擇合適的方式,才能讓 POST 提交更穩定且易於維護。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved