/** * @file internet.js * @version 20170829 fk * @type JS * * Komponente zum Ausführen von HTTP-Requests */ /** * @class KInternet */ var KInternet=function(){}; /** * @fn HTTPRequest * @memberof KInternet * @param {string} url * @param {function} func * @param {string|FormData|array of String|Blob} body * @param {boolean} binary */ KInternet.HTTPRequest=function(url,func,body,binary){ var xhr=new XMLHttpRequest(); if(body){ xhr.open("POST",url,true); if(binary) xhr.responseType="arraybuffer"; if(typeof body==='string' || body instanceof String){ xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); }else if(typeof body==='object' && !(body instanceof FormData)){ var fd=new FormData(); for(var key in body) fd.append(key,typeof body[key]==='string' || body[key] instanceof String || body[key] instanceof Blob?body[key]:JSON.stringify(body[key])); body=fd; //for(var pair of fd.entries()) console.log(pair[0]+ ': '+ pair[1]); } }else{ xhr.open("GET",url,true); body=null; } xhr.onload=function(){ if(xhr.readyState===4){ if(xhr.status===200){ if(binary){ func(this.response); }else{ var d=this.responseXML; if(!d && this.getResponseHeader("content-type")==="application/json"){ try{ d=JSON.parse(this.responseText); }catch(e){alert("Error parsing JSON\n"+this.responseText);} } func(this.responseText,d); } }else console.error(this.statusText); } }; xhr.onerror=function(e){ console.error(this.statusText); }; xhr.send(body); }; /** * @fn EncodeUTF8(s) * @memberof KInternet * @param {string} s * @returns {String} */ KInternet.EncodeUTF8=function(s){ // DEPRECATED !!! console.log("KInternet.EncodeUTF8() is deprecated - use encodeURIComponent() instead!"); var u=""; for(var n=0;n127) && (c<2048)){ u+=String.fromCharCode((c>>6) | 192); u+=String.fromCharCode((c & 63) | 128); }else{ u+=String.fromCharCode((c>>12) | 224); u+=String.fromCharCode(((c>>6) & 63) | 128); u+=String.fromCharCode((c & 63) | 128); } } return u; }; /** * @fn EncodeURL(s) * @memberof KInternet * @param {string} s * @returns {String} */ KInternet.EncodeURL=function(s){ // DEPRECATED !!! console.log("KInternet.EncodeURL() is deprecated - use encodeURIComponent() instead!"); var t=""; var x=0; var regex=/(^[a-zA-Z0-9_.]*)/; while(x1 && match[1]!=""){ t+=match[1]; x+=match[1].length; }else{ if(s[x]==" ") t+="+"; else{ var charCode=s.charCodeAt(x); var hexVal=charCode.toString(16); t+="%"+(hexVal.length<2 ? "0" : "")+hexVal.toUpperCase(); } x++; } } return t; };