備忘錄_20160105(定位) 修改 回首頁

程式 2020-05-28 14:30:23 1590647423 100
JavaScript 用 form 來導向其他網頁

JavaScript 用 form 來導向其他網頁
function location_href_by_form(strUrl, oParameters, strMethod) 
{
  // 範例
  // location_href_by_form("http://something.com.tw/", {"name":"John", "age":"18", "sex":"male"}, "post");
  
  var strAcceptCharset="utf-8";

  // "application/x-www-form-urlencoded" (預設,空白變成+,特殊字元用16進位編碼)
  // "multipart/form-data" (檔案上傳)
  // "text/plain" (空白變成+,其餘不變)
  var strEnctype="application/x-www-form-urlencoded";

  strMethod = strMethod || "post";
  var strAction=strUrl;
  var strTarget="_self";

  var oForm = document.createElement("form");

  oForm.setAttribute("accept-charset", strAcceptCharset);
  oForm.setAttribute("enctype", strEnctype);
  oForm.setAttribute("method", strMethod);
  oForm.setAttribute("action", strAction);
  oForm.setAttribute("target", strTarget);

  for(var strPropertyName in oParameters)
  {
    var strPropertyValue=oParameters[strPropertyName];

    var oHiddenField = document.createElement("input");
    oHiddenField.setAttribute("type", "hidden");
    oHiddenField.setAttribute("name", strPropertyName);
    oHiddenField.setAttribute("value", strPropertyValue);
    
    oForm.appendChild(oHiddenField);
  }
  
  document.body.appendChild(oForm);
  oForm.submit();
}