Notes arrangement of JavaScript working script

Keywords: Javascript JSON

Organize a JavaScript work script note in work, learn and save yourself.

(1) get Url absolute path

function getUrlRelativePath()
      {
        var url = document.location.toString();
        
        var arrUrl = url.split("//");

        var start = arrUrl[1].indexOf("/");
        var relUrl = arrUrl[1].substring(start);//stop omits, intercepts all characters from start to end

        if(relUrl.indexOf("?") != -1){
          relUrl = relUrl.split("?")[0];
        }
        return relUrl;
      }

(2) get Url request parameters

function GetRequest() {
  var url = location.search; //Get the string after the "? Character in the url
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for(var i = 0; i < strs.length; i ++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}
var Request = new Object();
Request = GetRequest();

(3) get specific request parameters

function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
// Call as follows:
alert(GetQueryString("Parameter name 1"));

(4) stringify function
To convert an existing object to a JSON string, you can use the JSON.stringify(obj) function

(5) setTimeOut function
javascript takes 3 seconds to execute method function
setTimeout(function(){ method()},3000);

(6) js gets the current day, month, hour, minute, second and week

$("#aa").click(function () {
var date = new Date();
this.year = date.getFullYear();
this.month = date.getMonth() + 1;
this.date = date.getDate();
this.day = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")[date.getDay()];
this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
var currentTime = "Now is:" + this.year + "year" + this.month + "month" + this.date + "day " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day;
alert(currentTime);
});

(7) Ajax request display prompt in loading

$.ajax({
    type: "post",
    url: loadurl,
    async: true,
    i:Math.random(),
    success:function(data){
        $("#tra_"+id).html(data);
    }
    beforeSend:function(){
        $("#Tra "+ ID). HTML ('loading... ');
    }
});

(8) a large number of if else... Alternative to

Need to write a lot of if else... In this case, the following hash dictionary matching method may be considered, or the state pattern may be used

Example:

/* Instead of if...else, change to hash dictionary matching method */
                        //if...else... Method
                        /* var itemTypeStr = '';
                        if(rowdata.itemType == '1'){
                            itemTypeStr = 'Administrative license ';
                        }else if(rowdata.itemType == '2'){
                            itemTypeStr = 'Non administrative license ';
                        }else if(rowdata.itemType == '3'){
                            itemTypeStr = 'Public service matters';
                        } */
                        var itemTypeReg = {
                                '0':'',
                                '1':'administrative licensing',
                                '2':'Non administrative license',
                                '3':'Public service matters',
                                '4':'Keep on record',
                                '5':'Other',
                                '6':'Administrative levy',
                                '7':'Administrative confirmation',
                                '8':'Administrative annual inspection',
                                '9':'Other administrative powers',
                                '10':'Administrative sanction',
                                '11':'Administrative coercion',
                                '12':'Administrative benefits',
                                '13':'Administrative examination',
                                '14':'Administrative reward',
                                '15':'Administrative adjudication'
                        }
                        var itemType = rowdata.itemType;
                        //Number with itemType of 1-15, hash matching method, examples for reference only
                        itemType = itemTypeReg[itemType];
                        return itemType;

(9) string length acquisition (Chinese supported)

To get the length of a string, sometimes str.length is used to get it directly. In fact, if there is no Chinese in the string, it is OK. But once there is Chinese, it will be found that such getting is not correct. Because Chinese takes up two bytes

function getStrRealLen(str) {
    ///< summary > get the actual length of string, Chinese 2, English 1 < / summary >
    ///< param name = "STR" > string to get the length < / param >
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
      charCode = str.charCodeAt(i);
      if (charCode >= 0 && charCode <= 128) realLength += 1;
      else realLength += 2;
    }
    return realLength;
  };

//q-u-n-784783012

Posted by dcooper on Sun, 08 Dec 2019 17:31:13 -0800