javascript Error reporting
Jak můžeme získat chyby na htm html stránce, které se projeví u uživatele v prohlížeči.
Ukážeme si příklad, který odešle zprávu o tom, že stránka je o 100px šiřší, jak uživatelova CLIENTAREA ( to, co vidí uživatel ze stránky) prohlížeče a také, že stránka nemá nastaven charset na UTF-8
Kód sestává ze javascriptu a php scriptu, který bude na serveru ukládat chybová hlášení.
Ukážeme si příklad, který odešle zprávu o tom, že stránka je o 100px šiřší, jak uživatelova CLIENTAREA ( to, co vidí uživatel ze stránky) prohlížeče a také, že stránka nemá nastaven charset na UTF-8
Kód sestává ze javascriptu a php scriptu, který bude na serveru ukládat chybová hlášení.
Nejdříve javascript
Tento script vložíme až na konec htm html (nebo inc php šablony kde je ukončení ) stránky mezi tagy /body a /html
</body>
<script type="text/javascript">
var s = new String();
var bUtf8 = false;
var m = document.getElementsByTagName("META");
for(var i = 0; i < m.length; i++){
s = m[i].content;
s = s.toLowerCase();
var nP = s.indexOf('charset');
var nPutf = s.indexOf('utf-8');
if(nP != (-1) && nPutf != (-1))
bUtf8 = true;
}
var httpRequestMy;
var sIE = "", sFF = "";
var nClientW = (parseInt(document.body.clientWidth));
var nScrollW = (parseInt(document.body.scrollWidth));
var nRozdil = nScrollW - nClientW;
if(nRozdil > 100 || bUtf8 == false){
// IE/zbytek sveta
if (window.ActiveXObject) {
httpRequestMy = new ActiveXObject("Microsoft.XMLHTTP");
sIE = "-IExplorer-";
} else {
httpRequestMy = new XMLHttpRequest();
sFF = "-Firefox-and-others-";
}
var d = new Date();
var url = "//myweb.com/stat/error.php?mess=<?php echo $_SERVER [SCRIPT_NAME];?>-pageWidth-"
+ nScrollW.toString() + "---clientWidth-" + nClientW.toString()
+ "-date-" + d.toDateString()+ "-" + d.toTimeString() + sFF + sIE;
if(bUtf8 == false)
url = "//myweb.com/stat/error.php?mess=<?php echo $_SERVER [SCRIPT_NAME];?>-UTF-8-false";
httpRequestMy.open("GET", url, true);
httpRequestMy.onreadystatechange= function () {processRequest(); } ;
httpRequestMy.send(null);
}
else {
//alert(nRozdil);
}
/****************/
function processRequest() {
if (httpRequestMy.readyState == 4) {
if(httpRequestMy.status == 200) {
var response = httpRequestMy.responseText;
if (response == 'EMPTY') {
alert('empty');
}
else {
//alert('OK');
}
}
}
else {
// alert("Error page loading "
// + httpRequestMy.status +":"+ httpRequestMy.statusText);
}
}
</script>
</html>
error.php může obsahovat takový kód
<?php
function vytvorNovyAzapisDoSouboru($fname, $poleVstup)
{ // BEGIN function vytvorNovyAzapisDoSouboru
if(file_exists($fname))unlink($fname);
$fp = fopen($fname, "a");
if (flock($fp, LOCK_EX)) { // do an exclusive lock
foreach ($poleVstup as $key=>$value) {
if(strlen($value)>5)
fwrite($fp, $value."
"); // D, d M Y
}
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't lock the file !";
}
fclose($fp);
chmod($fname, 0777);
} // END function vytvorNovyAzapisDoSouboru
$mess = $_GET['mess'];
$poleVstup = array();
if(file_exists('err_mess.txt')){
$poleVstup = file('err_mess.txt');
}
array_push($poleVstup, $mess);
//print_r($poleVstup);
vytvorNovyAzapisDoSouboru('err_mess.txt', $poleVstup);
?>
77LW NO topic_id
AD
Další témata ....(Topics)
Getter a Setter
Získej nebo Nastav.
Michal už není Váš kamarád, tak jej změníte pomocí set:
Získej nebo Nastav.
Třídy v javascript dovolují použití get a set instrukci.
get vrátí hodnotu určité zadané proměnné.
set jí může změnit.
class Person {
constructor(name) {
this.personName = name;
}
get pname() {
return this.personName;
}
// i kdyz set vypada jako funkce, musi mit pouze jeden parametr
set pname(x) {
this.personName = x;
}
}
var myFriend = new Person("Michael");
Jméno osoby přítele získáme například:
var strMyFriendName = myFriend.pname; // bez () na konci!!!!!!
alert(strMyFriendName);
Michal už není Váš kamarád, tak jej změníte pomocí set:
// hodnota se nepřirazuje do závorek (), ale pomocí = rovná se!!!!
myFriend.pname = "Renata";
strMyFriendName = myFriend.pname;
alert(strMyFriendName);
Example code
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.newsite.com/new-page.php");
header("Connection: close");
exit();
If using file name without .php as part of smoothly url - example:
$fileName = basename(__FILE__, '.php');
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.mysite.cz/auto-moto/".$fileName."/");
header("Connection: close");
exit();
Date: 23.07.2020 - 12:31Sqlite3 příkazy - rady zkušenosti
Tyto příkazy, začínající tečkou .neco viz https://sqlite.org/cli.html dávám buď do konzolové aplikace (Start - cmd), nebo příkazového řádku, nebo nejlépe do sql souboru, který otvírám přes bat soubor - viz níže.V samotném bat souboru se musí zápis upravovat a je to matoucí.
Výpis databáze do sql souboru lze snadno provést přes soubor s koncovkou bat. Je dobré si nakopírovat do adresáře soubor sqlite3.exe , nebo dle verze, ve které se pracuje.
Do _databaseToSql.bat zadám název (popř.cestu, pokud je databáze v jiné složce) databáze a soubor, do kterého bude vypsán sql.
_databaseToSql.bat
sqlite3 my_database.db .dump > output.sql
pause
Pro vykonání stačí na uložený _databaseToSql.bat dvojkliknout a provede se kod.
Plnění databáze ze souboru.sql
Opětovně output.sql můžeme použít pro vytvoření nové databáze a naplnit jí obsahem output.sql_sqlToDatabase.bat
sqlite3 new_database.sqlite < output.sql
pause
Plnění databáze ze souboru TXT, kde jednotlivé sloupce jsou odděleny středníkem
_txtFileToDatabase.bat
sqlite3 dictionary_database.db < load.sql
Do load.sql zadáme vytvoření tabulky a soubor.txt, ze kterého budeme plnit sloupce tabulky a čím jsou výrazy v txt souboru odděleny - v našem případě ; STŘEDNÍKEM.load.sql
CREATE TABLE [es_cz] (
[spanish] VARCHAR(255) NULL,
[czech] VARCHAR(255) NULL
);
.separator ";"
.import spanish-czech.txt es_cz
spanish-czech.txt pak bude obsahovat řádky oddělené ; středníkem.
spanish word;czech word
spanish word;czech word
spanish word;czech word
Výpis databáze do CSV souboru
Pokud chci zpět soubor CSV načíst do databáze, tak může nastat problém s oddělovačem sloupců - např. tam bude více ; středníků, či jiných oddělovačů na řádku, než kolik je sloupců a bude malér.Následující kód otevře myDatabase.db , vybere obsah tabulky myTable a vypíše jí do souboru test.csv
_databaseToCsvFile.bat
sqlite3.exe -header -csv myDatabase.db "select * from myTable;" > test.csv
Date: 19.04.2020 - 22:31
// multiline string old school tip trick
// create elemnt div style none or hidden with text
var sMulitilineString = document.getElementById('idHiddenDiv').innerHTML; // get text from hidden div
// ES6 with quotes
const htmlString = 'Say hello to
multi-line
strings!';
(typeof "813") // string
(typeof 813) // number
parseInt("10.33") // returns 10 string to integer
parseInt('2def8'); // 2
parseInt('a2def8'); // NaN
parseFloat("10.33") // returns 10.33 string to float
var test_1 = 'string';
var test_2 = ' example';
var suma = test_1 + test_2;
var length = suma.length; // 14
var le = test_1.length; // 6
charAt(index)
/* Returns the character at the specified index */
var str = new String('Sample');
str.charAt(3)); // p
// startsWith
var str = "HELLO WORLD";
var res = str.charAt(0); // H
// endsWith
var res = str.charAt(str.length - 1); // D
charCodeAt(index)
/* Returns an integer representing the Unicode encoding
of the character at the specified location */
var str = new String('Sample');
str.charCodeAt(3)); // 112
fromCharCode([code1[, code2[, ...[, codeN]]]])
/* Returns a string from a number of Unicode character values */
var e = window.event;
var str = String.fromCharCode(e.keyCode); // keydown etc.
concat([item1[, item2[, . . . [, itemN]]]])
/* Returns a new array consisting of a combination of two or more arrays */
var arr1 = new Array("Hello, ", "Dolly uranove");
var arr2 = new Array("World!", "dort");
var myConcatArray = arr1.concat(arr2);
alert(myConcatArray[3]); // dort
concat([string2[, string3[, . . . [, stringN]]]])
/* Returns a string value containing the concatenation
of two or more supplied strings */
var string1 = new String("Hello, ");
var string2 = new String("World!");
var myConcatString = string1.concat(string2); // Hello, World!
indexOf(subString[, startIndex])
/* Returns the character position where the first occurrence
of a substring occurs within a String object */
lastIndexOf(substring[, startindex])
/* Returns the last occurrence of a substring within a String object */
localeCompare(stringExp)
/* Returns a value indicating whether two strings
are equivalent in the current locale */
var str1 = "1";
var str2 = "2";
var n = str1.localeCompare(str2); // -1
var str1 = "2";
var str2 = "2";
var n = str1.localeCompare(str2); // 0
var str1 = "a";
var str2 = "b";
var n = str1.localeCompare(str2); // -1
var str1 = "b";
var str2 = "a";
var n = str1.localeCompare(str2); // 1
match(rgExp)
/* Executes a search on a string using a regular expression
pattern, and returns an array containing the results of that search */
var rgExp = /some text/g;
replace(rgExp, replaceText)
/* Returns a copy of a string with text replaced
using a regular expression or search string */
search(rgExp)
/* Returns the position of the first substring
match in a regular expression search */
n // A newline character
. // Any character except a newline
r // A carriage return character
t // A tab character
b // A word boundary (the start or end of a word)
B // Anything but a word boundary
d // Any digit (same as [0-9])
D // Anything but a digit (same as [^0-9])
s // Single whitespace (space, tab, newline, etc.)
S // Single nonwhitespace
w // A "word character” (same as [A-Za-z0-9_])
W // A "nonword character” (same as [^A-Za-z0-9_])
slice(start, [end])
/* Returns a section of an array or string */
var myString = new String("This is a test");
var mySlice = myString.slice(2,6); // is i // pos: 2 to 5 // 0==T, 1==h, 2==i, 3==s, 4==" ", 5==i
mySlice = myString.slice(-3); // est // end of string
mySlice = myString.slice(0); // This is a test
split([separator[, limit]])
/* Returns the array of strings that results
when a string is separated into substrings */
var str = "one two three";
var words = str.split(" ");
var len = words.length; // 3
substring(start, end)
/* Returns the substring at the specified location
within a String object */
var inpTxt = "Hello there";
alert(inpTxt.substring(6, 10)); // ther
substr(start [, length ])
// Returns a substring beginning at a specified
// location and having a specified length
var s = "The love in Spain.";
ss = s.substr(12, 5); // Spain
tolocaleLowerCase()
/* Returns a string where all alphabetic characters
have been converted to lowercase, taking into account
the host environment's current locale */
toUpperCase()
/* Returns a string where all alphabetic characters
have been converted to uppercase */
var myString = "My text";
myString.anchor //places an HTML anchor with a NAME attribute around specified text in the object
myString.big
myString.blink
myString.bold
myString.concat
myString.fixed
myString.fontcolor
myString.fontsize
myString.charAt
myString.charCodeAt
myString.indexOf
myString.italics
myString.lastindexOf
myString.length
myString.link
myString.match
myString.replace
myString.search
myString.slice
myString.small
myString.split
myString.strike
myString.sub //places HTML SUB tags around text in a String object
myString.substr
myString.substring
myString.sup
myString.toLowerCase
myString.toString
myString.toUpperCase
myString.valueOf
var str = "58";
var res = str.valueOf();
var type = (typeof res); // string
var str = 58;
var res = str.valueOf();
var type = (typeof res); // number
Editace: 18 10 2016
Počet článků v kategorii: 77
Url:javascript-error-reporting