Js if is not work in setInterval() - function

Hello!
I have This in my website:
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
alert('In next prompt enter "admin".')
var admin = prompt('Name?')
docCookies.setItem('name',admin);
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)
But this is not work:
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)
Why thi is not work:
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)
What in page not work and why?
I
<script type="text/javascript">
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
alert('In next prompt enter "admin".')
var admin = prompt('Name?')
docCookies.setItem('name',admin);
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)

The variable is declared locally in the function, so it only exists inside that scope, and only while the function is running.
Declare the variable in the global scope, so that you can set it and read it anywhere:
var a;
setInterval(function() {
if (!docCookies.getItem('name')) {
a = 2;
}
}, 1000)

Related

Extracting Google Meet URL from Google Calendar API [duplicate]

I want to create a line notify which can send the event detail from my google calendar everyday.
I can get the title, description, location...etc, but I don't see the conference data in calendar API.
I use Google Apps Script to run the code.
Here is my code.
const Now = new Date();
const Start = new Date(new Date().setHours(0, 0, 0, 0));
const End = new Date(new Date().setHours(23, 59, 59, 999));
const calendarData = calendar.getEvents(Start, End);
function Notify() {
var NotifyContents = '';
var i = 1;
calendarData.forEach(item =>{
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i+". "+ item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n": "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i+". "+ item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
if (typeof NotifyContents === 'string' && NotifyContents.length === 0) {
return;
}
NotifyTokens.forEach(function(value){
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", {
"method" : "post",
"payload" : {"message" : NotifyContents},
"headers" : {"Authorization" : "Bearer " + value}
});
});
}
Reference - Calendar API Link
In order to retrieve the meet link from the event, it seems that in the current stage, Calendar API is required to be used. When this is reflected in your script, how about the following modification?
Modified script:
Before you use this script, please enable Calendar API at Advanced Google services.
From:
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i + ". " + item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
To:
const eventList = Calendar.Events.list(calendar.getId(), { timeMin: Start.toISOString(), timeMax: End.toISOString(), maxResults: 2500 }).items.reduce((o, e) => (o[e.id] = e.conferenceData.entryPoints.map(({ uri }) => uri).join(","), o), {});
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
var eventId = item.getId().split("#")[0];
NotifyContents += eventList[eventId] != "" ? ("\n" + i + ". " + eventList[eventId]) : ("No Conference\n");
i++;
}
});
In this modification, it supposes that calendar has already been declaread. Please be careful about this.
Reference:
Events: list

Set Cookie through Google account? [duplicate]

This question already has answers here:
How do I create and read a value from cookie with javascript?
(23 answers)
Closed 8 years ago.
I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.
JavaScript code:
function cssLayout() {
document.getElementById("css").href = this.value;
}
function setCookie(){
var date = new Date("Februari 10, 2013");
var dateString = date.toGMTString();
var cookieString = "Css=document.getElementById("css").href" + dateString;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
HTML code:
<form>
Select your css layout:<br>
<select id="myList">
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
</form>
I find the following code to be much simpler than anything else:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Now, calling functions
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now.
These are much much better references than w3schools (the most awful web reference ever made):
How cookies work (quirksmode.org)
MDN document.cookie
Examples derived from these references:
// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
The Mozilla reference even has a nice cookie library you can use.
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.
Just use the setCookie and getCookie methods mentioned there.
So, the code will look something like:
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function cssSelected() {
var cssSelected = $('#myList')[0].value;
if (cssSelected !== "select") {
setCookie("selectedCSS", cssSelected, 3);
}
}
$(document).ready(function() {
$('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
<option value="select">--Select--</option>
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.
This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
Mozilla has some tests to prove this works in all cases.
There is an alternative snippet here:

Centering image in Excel

I've been trying to center an image in an Excel export file using Classic ASP. I tried everything and resorted to CSS. CSS didn't work (examples below):
img {
position: absolute;
top: 0; bottom:0; left: 0; right:0;
margin: auto;
}
and
img.center {
display: block;
margin: 0 auto;
}
I tried putting the image in a div and centering the div. That also didn't work. I have the image in an img tag like this:
<img border=0 id= "img" name= "img" src="pic.jpg" height ="100" width= "1000">
When I export the file to Excel and open it, the picture is always to the very left.
While simple Excel files can be created through ASP Classic simply by setting the headers for the page, you will often need more control.
Please take a look at this: http://www.crydust.be/blog/2009/03/02/generate-excel-files-in-asp-classic/
Code repostedform Kristof Neirynck's blog here:
<%#LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%>
<%
function getData(connectionString, sql){
var result = null;
var adStateOpen = 1;
var connection = new ActiveXObject("ADODB.CONNECTION");
try{
connection.Open(connectionString);
} catch(e1){
return null;
}
if (connection.State !== adStateOpen) {
return null;
}
try{
var recordset = connection.Execute(sql);
} catch(e2){
return null;
}
if (!recordset.EOF) {
result = recordset.GetRows().toArray();
recordset.Close();
}
recordset = null;
connection.Close();
connection = null;
return result;
}
function writeCsvHttpHeaders(filename){
Response.ContentType = "text/csv";
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition",
"attachment; filename="+filename+".csv");
}
function writeXlsHttpHeaders(filename){
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition",
"attachment; filename="+filename+".xls");
}
function getXlsStart(){
return ""
+ "<html>\n"
+ "<head>\n"
+ "<meta http-equiv=\"Content-Type\" "
+ "content=\"text/html; charset=UTF-8\">\n"
+ "<style type=\"text/css\">\n"
+ "html, body, table {\n"
+ " margin: 0;\n"
+ " padding: 0;\n"
+ " font-size: 11pt;\n"
+ "}\n"
+ "table, th, td { \n"
+ " border: 0.1pt solid #D0D7E5;\n"
+ " border-collapse: collapse;\n"
+ " border-spacing: 0;\n"
+ "}\n"
+ "</style>\n"
+ "</head>\n"
+ "<body>\n"
+ "<table>\n"
+ "";
}
function getXlsEnd(){
return ""
+ "</table>\n"
+ "</body>\n"
+ "</html>"
+ "";
}
function csvEscape(val){
if (typeof val === "number") {
return val.toString(10).replace(".", ",");
} else if (typeof val === "string") {
if (val.indexOf("\"") !== -1) {
return "\""+val.replace(/"/g, "\"\"")+"\"";
} else if (val.indexOf(";") !== -1) {
return "\""+val+"\"";
} else {
return val;
}
} else if (val === null) {
return "#NULL#";
} else if (val === undefined) {
return "#UNDEFINED#";
} else {
return "#ERROR#";
}
}
function writeCsv(filename, data, columnCount){
writeCsvHttpHeaders(filename);
// utf-8 BOM (very important for special characters)
Response.Write("\uFEFF");
for (var i=0, il=data.length; i<il; i+=columnCount) {
for (var j=0; j<columnCount; j++) {
Response.Write(csvEscape(data[i+j]));
if (j !== columnCount-1) {
Response.Write(";");
}
}
Response.Write("\n");
// prevent Response Buffering Limit Exceeded
if (i % 1000 === 0) {
Response.Flush();
}
}
}
function xlsEscape(val){
if (typeof val === "number") {
return val.toString(10).replace(".", ",");
} else if (typeof val === "string") {
return Server.HTMLEncode(val);
} else if (val === null) {
return "#NULL#";
} else if (val === undefined) {
return "#UNDEFINED#";
} else {
return "#ERROR#";
}
}
function writeXls(filename, data, columnCount){
writeXlsHttpHeaders(filename);
Response.Write(getXlsStart());
for (var i=0, il=data.length; i<il; i+=columnCount) {
Response.Write("<tr>");
for (var j=0; j<columnCount; j++) {
Response.Write("<td>");
Response.Write(xlsEscape(data[i+j]));
Response.Write("</td>");
}
Response.Write("</tr>\n");
// prevent Response Buffering Limit Exceeded
if (i % 1000 === 0) {
Response.Flush();
}
}
Response.Write(getXlsEnd());
}
function main(){
var filetype = Request.QueryString("filetype")();
Var connectionString = "Provider=SQLOLEDB.1;"
+ "Data Source=LAPTOP\\SQLEXPRESS;"
+ "User ID=internal;"
+ "Password=internal;"
+ "Initial Catalog=trees_in_sql";
Var sql = ""
+ "SELECT id \n"
+ ", name \n"
+ "FROM People \n"
+ ";";
var filename = "filename";
var columnCount = 2;
var data = getData(connectionString, sql);
if (data !== null) {
Response.Clear();
if (filetype === "csv") {
writeCsv(filename, data, columnCount);
} else {
writeXls(filename, data, columnCount);
}
} else {
Response.Write("Error, no data found");
}
Response.End();
}
main();
%>
.
IMPORTANT
Regarding images specifically, you should look at this: http://www.experts-exchange.com/Programming/Languages/Scripting/ASP/Q_27115638.html
From the above link:
<!--#include file="functions.asp"-->
<%
response.ContentType = "application/vnd.ms-excel"
thedate = CStr(Now())
groupid = request.querystring("groupid")
GroupName = getGroupName(groupid)
datetimestring = Replace(FormatDateTime(Now(), vbShortDate), "/", "-") & "_" & Replace(FormatDateTime(Now(), vbShortTime), ":", "")
response.AddHeader "Content-Disposition", "attachment;filename=GroupAttendanceExport_" & GroupName & "_" & datetimestring & ".xls"
response.write "<html><body><table>"
response.write "<tr><td><img border=0 src='https://www.example.org/xxx_Logo_small.jpg'></td></tr>"
response.write "<tr><td></td></tr>"
response.write "<tr><td></td></tr>"
response.write "<tr><td></td></tr>"
response.write "<tr><td></td></tr>"
response.write "<tr><td></td></tr>"
response.write "<tr><td > Attendance</td></tr>"
response.write "</table>"
MORE CODE HERE
………
………
………
………
response.write "</body></html>"
.
UPDATE
It sounds like you need to use OpenXML instead of HTML.
Here is an example of how to insert an image into a specific cell using OpenXML: https://social.msdn.microsoft.com/Forums/office/en-US/157e2fab-ed30-43a5-9824-e144d673a5b7/insert-images-into-specific-excel-cells-using-openxml?forum=oxmlsdk

Parse JSON string containing a colon

The class I am using to parse JSON does not allow you to have colons in any string. For example, this would cause an error in parsing:
{
"Test:": "Just a test"
}
Any ideas on how to make this class ignore colons that are in a string? Here is the class I am using:
class JSON {
static var inst;
var text;
function JSON() {
}
static function getInstance() {
if (inst == null) {
inst = new cinqetdemi.JSON();
}
return (inst);
}
static function stringify(arg) {
var _local3;
var _local2;
var _local6;
var _local1 = "";
var _local4;
switch (typeof (arg)) {
case "object" :
if (arg) {
if (arg instanceof Array) {
_local2 = 0;
while (_local2 < arg.length) {
_local4 = stringify(arg[_local2]);
if (_local1) {
_local1 = _local1 + ",";
}
_local1 = _local1 + _local4;
_local2++;
}
return (("[" + _local1) + "]");
} else if (typeof (arg.toString) != "undefined") {
for (_local2 in arg) {
_local4 = arg[_local2];
if ((typeof (_local4) != "undefined") && (typeof (_local4) != "function")) {
_local4 = stringify(_local4);
if (_local1) {
_local1 = _local1 + ",";
}
_local1 = _local1 + ((stringify(_local2) + ":") + _local4);
}
}
return (("{" + _local1) + "}");
}
}
return ("null");
case "number" :
return ((isFinite(arg) ? (String(arg)) : "null"));
case "string" :
_local6 = arg.length;
_local1 = "\"";
_local2 = 0;
while (_local2 < _local6) {
_local3 = arg.charAt(_local2);
if (_local3 >= " ") {
if ((_local3 == "\\") || (_local3 == "\"")) {
_local1 = _local1 + "\\";
}
_local1 = _local1 + _local3;
} else {
switch (_local3) {
case "\b" :
_local1 = _local1 + "\\b";
break;
case "\f" :
_local1 = _local1 + "\\f";
break;
case newline :
_local1 = _local1 + "\\n";
break;
case "\r" :
_local1 = _local1 + "\\r";
break;
case "\t" :
_local1 = _local1 + "\\t";
break;
default :
_local3 = _local3.charCodeAt();
_local1 = _local1 + (("\\u00" + Math.floor(_local3 / 16).toString(16)) + (_local3 % 16).toString(16));
}
}
_local2 = _local2 + 1;
}
return (_local1 + "\"");
case "boolean" :
return (String(arg));
}
return ("null");
}
static function parse(text) {
if (!text.length) {
throw new Error("JSONError: Text missing");
}
var _local1 = getInstance();
_local1.at = 0;
_local1.ch = " ";
_local1.text = text;
return (_local1.value());
}
function error(m) {
var _local2 = ((("JSONError: " + m) + " at ") + (at - 1)) + newline;
_local2 = _local2 + (text.substr(at - 10, 20) + newline);
_local2 = _local2 + " ^";
throw new Error(_local2);
}
function next() {
ch = text.charAt(at);
at = at + 1;
return (ch);
}
function white() {
while (ch) {
if (ch <= " ") {
next();
} else if (ch == "/") {
switch (next()) {
case "/" :
while ((next() && (ch != newline)) && (ch != "\r")) {
}
break;
case "*" :
next();
while (true) {
if (ch) {
if (ch == "*") {
if (next() == "/") {
next();
break;
}
} else {
next();
}
} else {
error("Unterminated comment");
}
}
break;
default :
error("Syntax error");
}
} else {
break;
}
}
}
function str() {
var _local5;
var _local2 = "";
var _local4;
var _local3;
var _local6 = false;
if ((ch == "\"") || (ch == "'")) {
var _local7 = ch;
while (next()) {
if (ch == _local7) {
next();
return (_local2);
} else if (ch == "\\") {
switch (next()) {
case "b" :
_local2 = _local2 + "\b";
break;
case "f" :
_local2 = _local2 + "\f";
break;
case "n" :
_local2 = _local2 + newline;
break;
case "r" :
_local2 = _local2 + "\r";
break;
case "t" :
_local2 = _local2 + "\t";
break;
case "u" :
_local3 = 0;
_local5 = 0;
while (_local5 < 4) {
_local4 = parseInt(next(), 16);
if (!isFinite(_local4)) {
_local6 = true;
break;
}
_local3 = (_local3 * 16) + _local4;
_local5 = _local5 + 1;
}
if (_local6) {
_local6 = false;
break;
}
_local2 = _local2 + String.fromCharCode(_local3);
break;
default :
_local2 = _local2 + ch;
}
} else {
_local2 = _local2 + ch;
}
}
}
error("Bad string");
}
function key() {
var _local2 = ch;
var _local6 = false;
var _local3 = text.indexOf(":", at);
var _local4 = text.indexOf("\"", at);
var _local5 = text.indexOf("'", at);
if (((_local4 <= _local3) && (_local4 > -1)) || ((_local5 <= _local3) && (_local5 > -1))) {
_local2 = str();
white();
if (ch == ":") {
return (_local2);
} else {
error("Bad key");
}
}
while (next()) {
if (ch == ":") {
return (_local2);
}
if (ch <= " ") {
} else {
_local2 = _local2 + ch;
}
}
error("Bad key");
}
function arr() {
var _local2 = [];
if (ch == "[") {
next();
white();
if (ch == "]") {
next();
return (_local2);
}
while (ch) {
if (ch == "]") {
next();
return (_local2);
}
_local2.push(value());
white();
if (ch == "]") {
next();
return (_local2);
} else if (ch != ",") {
break;
}
next();
white();
}
}
error("Bad array");
}
function obj() {
var _local3;
var _local2 = {};
if (ch == "{") {
next();
white();
if (ch == "}") {
next();
return (_local2);
}
while (ch) {
if (ch == "}") {
next();
return (_local2);
}
_local3 = this.key();
if (ch != ":") {
break;
}
next();
_local2[_local3] = value();
white();
if (ch == "}") {
next();
return (_local2);
} else if (ch != ",") {
break;
}
next();
white();
}
}
error("Bad object");
}
function num() {
var _local2 = "";
var _local3;
if (ch == "-") {
_local2 = "-";
next();
}
while (((((ch >= "0") && (ch <= "9")) || (ch == "x")) || ((ch >= "a") && (ch <= "f"))) || ((ch >= "A") && (ch <= "F"))) {
_local2 = _local2 + ch;
next();
}
if (ch == ".") {
_local2 = _local2 + ".";
next();
while ((ch >= "0") && (ch <= "9")) {
_local2 = _local2 + ch;
next();
}
}
if ((ch == "e") || (ch == "E")) {
_local2 = _local2 + ch;
next();
if ((ch == "-") || (ch == "+")) {
_local2 = _local2 + ch;
next();
}
while ((ch >= "0") && (ch <= "9")) {
_local2 = _local2 + ch;
next();
}
}
_local3 = Number(_local2);
if (!isFinite(_local3)) {
error("Bad number");
}
return (_local3);
}
function word() {
switch (ch) {
case "t" :
if (((next() == "r") && (next() == "u")) && (next() == "e")) {
next();
return (true);
}
break;
case "f" :
if ((((next() == "a") && (next() == "l")) && (next() == "s")) && (next() == "e")) {
next();
return (false);
}
break;
case "n" :
if (((next() == "u") && (next() == "l")) && (next() == "l")) {
next();
return (null);
}
break;
}
error("Syntax error");
}
function value() {
white();
switch (ch) {
case "{" :
return (obj());
case "[" :
return (arr());
case "\"" :
case "'" :
return (str());
case "-" :
return (num());
}
return ((((ch >= "0") && (ch <= "9")) ? (num()) : (word())));
}
var at = 0;
var ch = " ";
}
Take a look on my answer of this question and use the JSON class that I mentioned there, it's working fine with your test content :
import JSON;
var json = new JSON();
var data:String = '{"Test:": "Just a test"}';
trace(json.parse(data)['Test:']); // gives : Just a test
Hope that can help.

IE 8 - Invalid source HTML for this operation

What is wrong with
el.insertAdjacentHTML(hashVal[0], html);
where html is "<a title=\"\">1</a>" and hashVal[0] is "afterBegin".
This is related to a rating functionality. I think due to this error, the rating star is not displaying in ie 8. Other browsers are ok.
I have given the full flow of code below. I am using extjs.
var starLink = star.createChild({
tag: 'a',
html: this.values[i],
title: this.showTitles ? this.titles[i] : ''
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
createChild : function(config, insertBefore, returnDom) {
config = config || {tag:'div'};
if (insertBefore) {
return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
}
else {
return Ext.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true);
}
},
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
insertFirst : function(el, o, returnElement){
return doInsert(el, o, returnElement, afterbegin, 'firstChild');
},
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function doInsert(el, o, returnElement, pos, sibling, append){
el = Ext.getDom(el);
var newNode;
if (pub.useDom) {
newNode = createDom(o, null);
if (append) {
el.appendChild(newNode);
} else {
(sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
}
} else {
newNode = Ext.DomHelper.insertHtml(pos, el, Ext.DomHelper.createHtml(o));
}
return returnElement ? Ext.get(newNode, true) : newNode;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createHtml(o){
var b = '',
attr,
val,
key,
cn,
i;
if(typeof o == "string"){
b = o;
} else if (Ext.isArray(o)) {
for (i=0; i < o.length; i++) {
if(o[i]) {
b += createHtml(o[i]);
}
}
} else {
b += '<' + (o.tag = o.tag || 'div');
for (attr in o) {
val = o[attr];
if(!confRe.test(attr)){
if (typeof val == "object") {
b += ' ' + attr + '="';
for (key in val) {
b += key + ':' + val[key] + ';';
}
b += '"';
}else{
b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
}
}
}
if (emptyTags.test(o.tag)) {
b += '/>';
} else {
b += '>';
if ((cn = o.children || o.cn)) {
b += createHtml(cn);
} else if(o.html){
b += o.html;
}
b += '</' + o.tag + '>';
}
}
return b;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
insertHtml : function(where, el, html){
var hash = {},
hashVal,
range,
rangeEl,
setStart,
frag,
rs;
where = where.toLowerCase();
hash[beforebegin] = ['beforeBegin', 'previousSibling'];
hash[afterend] = ['afterEnd', 'nextSibling'];
if (el.insertAdjacentHTML) {
if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
return rs;
}
hash[afterbegin] = ['afterBegin', 'firstChild'];
hash[beforeend] = ['beforeEnd', 'lastChild'];
if ((hashVal = hash[where])) {
el.insertAdjacentHTML(hashVal[0], html);
return el[hashVal[1]];
}
} else {