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

程式 2023-03-12 08:51:44 1678582304 100
JavaScript常用類別參考

JavaScript常用類別參考
  1. gebi(strId)
  2. getStrUUID()
  3. location_href_by_form(strUrl, oParameters, strMethod)
  4. showOrHide(strId)
  5. toast(strMessage, iInterval)
  6. async msgbox(strMsg, straBtn)
  7. async inputbox(strPrompt, strDefaultValue)
  8. makeAnXhr(oParameters)
  9. makeAnXhr_form_post(oParameters)

class c_liujiaje_com_common
{
  gebi(strId)
  {
    return document.getElementById(strId);
  }
  
  getStrUUID()
  {
    var d = Date.now();
    if (typeof performance !== 'undefined' 
    && typeof performance.now === 'function')
    {
      d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace
    (
      /[xy]/g, 
      function (c) 
      {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
      }
    );
  }
  
  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();
  }
  
  showOrHide(strId)
  {
    var obj1=this.gebi(strId);
    if(obj1)
    {
      if(obj1.style.display=="none") { obj1.style.display=""; }
      else                           { obj1.style.display="none"; }
    }
  }
  
  toast(strMessage, iInterval)
  {
    if(!iInterval) { iInterval=3000; }
    
    var oToast=document.createElement("div");
    oToast.style.display="block";
    oToast.style.position="fixed";
    oToast.style.zIndex="1";
    oToast.style.visibility="visible";
    oToast.style.width="100%";
    oToast.style.textAlign="center";
    oToast.style.bottom="30px";
    oToast.style.fontSize="17px";
    
    var straStyle=[];
    straStyle.push("display: inline-block");
    straStyle.push("color: #ffffff");
    straStyle.push("background-color: #333");
    straStyle.push("margin: 0 auto");
    straStyle.push("border-radius: 2px");
    straStyle.push("padding: 16px");
    oToast.innerHTML
      ="<div style='"+straStyle.join("; ")+"'>"
      +strMessage
      +"</div>";
    document.body.appendChild(oToast);
    
    setTimeout(function() { oToast.parentNode.removeChild(oToast); }, iInterval);
  }
  
  async msgbox(strMsg, straBtn)
  {
    // // 呼叫範例
    //
    // async function main()
    // {
    //   var strRtn=await msgbox("對話框測試!<br>第二行在這裡!", ["確定", "取消"]);
    //   console.log(strRtn);
    // }
          
    if(Array.isArray(straBtn)==false || straBtn.length<1)
    {
      straBtn=["確定"];
      // straBtn=["確定", "取消"];
    }
    
    var strRtn="";
    
    await new Promise
    (
      (成功, 失敗)=>
      {
        // 背景
        var oBG=document.createElement("div");
        oBG.style.display="block";
        oBG.style.position="fixed";
        oBG.style.zIndex="1";
        oBG.style.left="0";
        oBG.style.top="0";
        oBG.style.width="100%";
        oBG.style.height="100%";
        oBG.style.overflow="auto";
        oBG.style.backgroundColor="rgb(0,0,0)";
        oBG.style.backgroundColor="rgba(0,0,0,0.4)";
        oBG.style.textAlign="center";
      
        // 前景
        var oFG=document.createElement("div");
        oFG.style.display="inline-block";
        oFG.style.backgroundColor="rgb(240,240,240)";
        oFG.style.margin="0 auto";
        oFG.style.padding="1em";
        oFG.style.borderStyle="solid";
        oFG.style.borderWidth="1px";
        oFG.style.borderColor="#888888";
        oFG.style.borderRadius="12px";
        oFG.style.textAlign="center";
      
        // 內文
        var oContent=document.createElement("div");
        oContent.style.margin="4px";
        oContent.innerHTML=strMsg;
        oFG.appendChild(oContent);
        
        // 產生按鈕
        for(var i=0; i<straBtn.length; i++)
        {
          var oTmpBtn=document.createElement("button");
          oTmpBtn.setAttribute("type","button");
          oTmpBtn.innerHTML=straBtn[i];
          oTmpBtn.setAttribute("returnString",straBtn[i]);
          oTmpBtn.style.margin="4px";
          oTmpBtn.onclick=function()
          {
            strRtn=this.getAttribute("returnString");
            成功(oBG);
          }
          oFG.appendChild(oTmpBtn);
        }
        
        // 把前景加入到背景裡頭
        oBG.appendChild(oFG);
        
        // 把背景加入到 body 中
        document.body.appendChild(oBG);
        
        // 點到背景灰黑的部分,等同按下取消。
        window.addEventListener("click",function(event)
        {
          if(event.target==oBG)
          {
            strRtn=straBtn[straBtn.length-1];
            成功(oBG);
          }
        },false);
        
        // oBG.style.display="block";
        
        // 垂直置中
        oFG.style.marginTop=((window.innerHeight-oFG.offsetHeight)/2)+"px";
        
        oTmpBtn.focus();
      }
    )
    .then(  (oBG)=>{ oBG.parentNode.removeChild(oBG); } )
    .catch( (err)=>{ strRtn="err:"+err; console.log(strRtn); } );
    
    return strRtn;
  }
  
  async inputbox(strPrompt, strDefaultValue)
  {
    // // 呼叫範例
    //
    // async function main()
    // {
    //   var strRtn=await inputbox("請您輸入資料", "預設值");
    //   console.log(strRtn);
    // }
    
    if(!strDefaultValue) { strDefaultValue=''; }
    
    var strRtn="";
    
    await new Promise
    (
      (成功, 失敗)=>
      {
        // 背景
        var oBG=document.createElement("div");
        oBG.style.display="block";
        oBG.style.position="fixed";
        oBG.style.zIndex="1";
        oBG.style.left="0";
        oBG.style.top="0";
        oBG.style.width="100%";
        oBG.style.height="100%";
        oBG.style.overflow="auto";
        oBG.style.backgroundColor="rgb(0,0,0)";
        oBG.style.backgroundColor="rgba(0,0,0,0.4)";
        oBG.style.textAlign="center";
      
        // 前景
        var oFG=document.createElement("div");
        oFG.style.display="inline-block";
        oFG.style.backgroundColor="rgb(240,240,240)";
        oFG.style.margin="0 auto";
        oFG.style.padding="1em";
        oFG.style.borderStyle="solid";
        oFG.style.borderWidth="1px";
        oFG.style.borderColor="#888888";
        oFG.style.borderRadius="12px";
        oFG.style.textAlign="center";
      
        // 提示
        var oPrompt=document.createElement("div");
        oPrompt.style.margin="4px";
        oPrompt.innerHTML=strPrompt;
        oFG.appendChild(oPrompt);
        
        // 輸入方框
        var oInput=document.createElement("input");
        oInput.setAttribute("type", "text");
        oInput.setAttribute("value", strDefaultValue);
        // 若是用 onkeyup, onkeydown 則注音輸入法的 Enter 會被攔截到
        oInput.onkeypress=function(keyboardEvent)
        {
          if(keyboardEvent.keyCode==13 || keyboardEvent.key=="Enter")
          {
            strRtn=oInput.value;
            成功(oBG);
          }
        }
        
        var oContent=document.createElement("div");
        oContent.style.margin="4px";
        oContent.appendChild(oInput);
        
        oFG.appendChild(oContent);
        
        // 產生按鈕
        var straBtn=["確定", "取消"];
        for(var i=0; i<straBtn.length; i++)
        {
          var oTmpBtn=document.createElement("button");
          oTmpBtn.setAttribute("type","button");
          oTmpBtn.innerHTML=straBtn[i];
          oTmpBtn.setAttribute("returnString",straBtn[i]);
          oTmpBtn.style.margin="4px";
          
          if(i==0)
          {
            oTmpBtn.onclick=function()
            {
              strRtn=oInput.value;
              成功(oBG);
            }
          }
          else
          {
            oTmpBtn.onclick=function()
            {
              strRtn="";
              成功(oBG);
            }
          }
          oFG.appendChild(oTmpBtn);
        }
        
        // 把前景加入到背景裡頭
        oBG.appendChild(oFG);
        
        // 把背景加入到 body 中
        document.body.appendChild(oBG);
        
        // 點到背景灰黑的部分,等同按下取消。
        window.addEventListener("click",function(event)
        {
          if(event.target==oBG)
          {
            strRtn="";
            成功(oBG);
          }
        },false);
        
        // oBG.style.display="block";
        
        // 垂直置中
        oFG.style.marginTop=((window.innerHeight-oFG.offsetHeight)/2)+"px";
        
        oTmpBtn.focus();
      }
    )
    .then(  (oBG)=>{ oBG.parentNode.removeChild(oBG); } )
    .catch( (err)=>{ strRtn="err:"+err; console.log(strRtn); } );
    
    return strRtn;
  }
  
  makeAnXhr(oParameters)
  {
    // // 範例參考
    // 
    // var oP={};
    // oP.strMethod="post"; // get 或 post
    // oP.strAction="a.php";
    // oP.strContentType="application/x-www-form-urlencoded; charset=UTF-8";
    // oP.straPairs=[
    //   ["name","John"],
    //   ["age","18"],
    //   ["salary","28000"],
    //   ["special","'\"=&?甚麼都來!"]
    // ];
    // oP.callbackSuccess=function(oXhr) { console.log(oXhr.responseText); };
    // oP.callbackFailure=function(oXhr) { console.log("error"+oXhr.status); };
    // makeAnXhr(oP);
    
    // 傳遞參數
    var straTmp=[];
    if(oParameters.hasOwnProperty("straPairs")==true)
    {
      for(i=0; i<oParameters.straPairs.length; i++)
      { 
        straTmp.push
        (
          encodeURIComponent(oParameters.straPairs[i][0])
          + "=" 
          + encodeURIComponent(oParameters.straPairs[i][1])
        );
      }
    }
    var strEncodedParameters=straTmp.join("&");
    
    var strAttachParameters4Get="";
    var strAttachParameters4Post="";
    if(oParameters.strMethod=="get")  { strAttachParameters4Get="?"+strEncodedParameters; }
    if(oParameters.strMethod=="post") { strAttachParameters4Post=strEncodedParameters; }
    
    // 內容型態
    if(oParameters.hasOwnProperty('strContentType')==false)
      { oParameters.strContentType="application/x-www-form-urlencoded; charset=UTF-8"; }
    
    // 準備 XMLHttpRequest
    const oXhr=new XMLHttpRequest();
    
    oXhr.open(
      oParameters.strMethod.toUpperCase(), 
      oParameters.strAction+strAttachParameters4Get, 
      true); // true:async, false;sync
      
    oXhr.setRequestHeader("Content-Type", oParameters.strContentType);
    oXhr.onreadystatechange=function()
    {
      if(oXhr.readyState===XMLHttpRequest.DONE)
      {
        var status=oXhr.status;
        if(status===0 || (status>=200 && status<400))
        {
          oParameters.callbackSuccess(oXhr);
        }
        else
        {
          oParameters.callbackFailure(oXhr);
        }
      }
    }
    
    oXhr.send(strAttachParameters4Post);
  }
  
  makeAnXhr_form_post(oParameters)
  {
    // // 若有要上傳檔案,則此方法就很好用!
    // 
    // // 範例參考
    // 
    // var oP={};
    // oP.strAction="a.php";
    // oP.oFormElement=document.getElementById('myForm');
    // oP.callbackSuccess=function(oXhr) { console.log(oXhr.responseText); };
    // oP.callbackFailure=function(oXhr) { console.log("error"+oXhr.status); };
    // makeAnXhr_form_post(oP);
    
    // 準備 XMLHttpRequest
    const oXhr=new XMLHttpRequest();
    
    oXhr.open("POST", oParameters.strAction, true); // true:async, false;sync
      
    oXhr.onreadystatechange=function()
    {
      if(oXhr.readyState===XMLHttpRequest.DONE)
      {
        var status=oXhr.status;
        if(status===0 || (status>=200 && status<400))
          { oParameters.callbackSuccess(oXhr); }
        else
          { oParameters.callbackFailure(oXhr); }
      }
    }
    
    oXhr.send(new FormData(oParameters.oFormElement));
  }
  
}