I should loop this json file to javascript, all the entries are important and must be retrieved.
I need to make this json compatible with this javascript code.
This is my json file:
{ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
This is my code javascript:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
var user_token = arr[0].user_token;
for(i = 0; i < arr.length; i++) {
var level = arr[i].level;
out += user_token;
}
document.getElementById("id01").innerHTML = out;
}
var jsonInput={ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
function myFunction(arr) {
var out = "";
var i;
var userLabel=''
var user_token = arr.user_token;
mainArrObj=arr.main_levels
for(i = 0; i < mainArrObj.length; i++) {
var level = mainArrObj[i].level;
out += user_token + ' ';
userLabel += level + ' ';
}
console.log('user_token :'+out);
console.log('userLabel :'+userLabel);
}
myFunction(jsonInput)
Related
How can I loop my json file using my script, eg: I should choose whether to loop Schema A or Schema B.
My json file is:
{
"A":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
],
"B":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
]
}
Maybe setting a variable so as to define the scheme I have to display
My javascript file is:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj= JSON.parse(this.responseText);
myFunction(obj, 'A');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj, key) {
var arr = obj[key];
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
Assuming that what you presented as JSON file is a response form network and is passed to myFunction, then why not to do something like:
let myRootArray;
if(/* some confitions */) {
myRootArray = myArr.A
} else {
myRootArray = myArr.B
}
myFunction(myRootArray );
Beside that, your names are a bit confusing, var myArr = JSON.parse(this.responseText);, while JSON.parse will return object, not an array.
I want to get a file from client side to parse it into json object and send it to the backend, i am able to parse the file thanks to Sheet-js.
My problem is i can not get files from client side
I am using js, SAPUI5
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
if (!oFileUploader.getValue().toString()) {
MessageToast.show("Choose a xlsx file first");
return;
}
var url = "/resources/test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = [];
for (var i = 0; i !== data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {
type: "binary"
});
var firstSheetName = workbook.SheetNames[0];
var worksheet = workbook.Sheets[firstSheetName];
var json = XLSX.utils.sheet_to_json(worksheet, {
raw: true
});
var jsonStr = JSON.stringify(json);
MessageBox.show("JSON String: " + jsonStr);
};
oReq.send();
},
The answer is:
UploadFile.view.xml
<VBox>
<u:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}
I am in the process of creating a listview from JSON data however, after calling an 'onclick' function from a For loop, the link, which opens up in a new window, loads three URLs into the URL input of the browser. Any idea how I could re-work the below code to just load one link rather that the three based on the below code?
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 += arr[i].timetable_1_link;
URL_2 += arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can start by refactoring the function that opens the URL to accept a parameter like this:
function openLinkInNewWindow_1(URL) {
window.open(URL, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
Then in the for loop pass the URL along with each link.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
This way you only need the one function. Notice also that I removed the + from the URL_1 += line.
Using URL_1+= is culprit here. Every time loops run it appends new string to existing url(s).
So remove += from URL_ variables in your function 'myFunction' and assign values directly by using '=' only.
Updated code is written below
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can take a look for updated and running code here
I am trying to append an image into a span, it works perfectly outputting the image path as text using:
homeTeamName_span.appendChild(homeTeamName_crest);
However, when trying to wrap image tags around it, it doesn't do anything and no data will load because of it.
What would be the reason for this?
homeTeamName_span.appendChild("<img src='homeTeamName_crest' />");
Function source
window.onload = function() {
var xmlhttp = new XMLHttpRequest();
var url = "http://bushell.net/football/site/includes/webservice.php?service=allfixtures&limit=10&competition=427";
var url2 = "http://bushell.net/football/site/includes/webservice.php?service=allfixtures&limit=10&competition=426"
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getECL(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function getECL(response) {
var ECL_arr = JSON.parse(response);
var i;
//add 6hrs
var ecl_games = document.getElementById("ecl-games");
for(i = 0; i < ECL_arr.length; i++) {
var gameInfo_container = document.createElement("LI");
ecl_games.appendChild(gameInfo_container);
var homeTeamName_span = document.createElement("SPAN");
homeTeamName_span.className = "text-right";
var homeTeamName_text = document.createTextNode(ECL_arr[i].homeTeamName);
homeTeamName_span.appendChild(homeTeamName_text);
gameInfo_container.appendChild(homeTeamName_span);
var date_span = document.createElement("SPAN");
date_span.className = "d-g";
var date_span_text = document.createTextNode(ECL_arr[i].date);
date_span.appendChild(date_span_text);
gameInfo_container.appendChild(date_span);
var awayTeamName_span = document.createElement("SPAN");
awayTeamName_span.className = "text-left";
var awayTeamName_text = document.createTextNode(ECL_arr[i].awayTeamName);
awayTeamName_span.appendChild(awayTeamName_text);
gameInfo_container.appendChild(awayTeamName_span);
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getPrem(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();
function getPrem(response){
var prem_arr = JSON.parse(response);
var prem_games = document.getElementById("prem-games");
for(var j = 0; j<prem_arr.length; j++) {
var gameInfo_container = document.createElement("LI");
prem_games.appendChild(gameInfo_container);
var homeTeamName_span = document.createElement("SPAN");
homeTeamName_span.className = "text-right";
var homeTeamName_text = document.createTextNode(prem_arr[j].homeTeamName);
var homeTeamName_crest = document.createTextNode(prem_arr[j].homeTeamCrest);
homeTeamName_span.appendChild("<img src='homeTeamName_crest' />");
homeTeamName_span.appendChild(homeTeamName_text);
gameInfo_container.appendChild(homeTeamName_span);
var date_span = document.createElement("SPAN");
date_span.className = "d-g";
var date_span_text = document.createTextNode(prem_arr[j].date);
date_span.appendChild(date_span_text);
gameInfo_container.appendChild(date_span);
var awayTeamName_span = document.createElement("SPAN");
awayTeamName_span.className = "text-left";
var awayTeamName_text = document.createTextNode(prem_arr[j].awayTeamName);
awayTeamName_span.appendChild(awayTeamName_text);
gameInfo_container.appendChild(awayTeamName_span);
}
console.log("loop finished");
}
}
this shoud work , if homeTeamName_crest is the path of the picture
$(homeTeamName_span).append("<img src='"+homeTeamName_crest+"' />")
What if you do this?
var homeTeamName_crest = prem_arr[j].homeTeamCrest; // <--- change this line, don't make it a textNode
homeTeamName_span.appendChild("<img src='" + homeTeamName_crest + '/>"); // <--- change this line, we want to interpolate the string as the path to the image
Alright, so I got this xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<level>
<tiles>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1111111111111111</row>
</tiles>
</level>
and I got my XML reading code:
var xmlDoc = document.implementation.createDocument("","",null);
and
function loadXML(){
xmlDoc.load("levels/test.xml");
xmlDoc.onload = readLevel();
}
function readLevel() {
throw(xmlDoc);
if(xmlDoc.getElementsByTagName("tiles")[0].hasChildNodes()){
var rowNum = xmlDoc.getElementsByTagName("tiles").getChildNodes();
level = [];
for(var i = 0; i < rowNum; i++){
level[i] = [];
var tempStr = xmlDoc.getElementsByTagName("tiles").childNodes[i].textContent;
for(var j = 0; j < 16; j++){
level[i][j] = parceInt(tempStr.charAt(j));
}
}
}
for (var i = 0; i < level.length; i++) {
blockArray[i] = []; // Create the second level for this index
for (var j = 0; j < level[i].length; j++) {
var tempImg = new Image();
tempImg.src = "images/block" + level[i][j] + ".png";
blockArray[i][j] = new block(j * blockSize, i * blockSize, level[i][j], false, false, tempImg);
//throw('blockArray['+i+']'+j+'] = ' + level[i][j]);
}
}
}
Now why isn't this working? It constantly says xmlDoc.getElementsByTagName("tiles")[0] is undefined and that xmlDoc.getElementsByTagName("tiles").length = 0. So what am I doing wrong?
I'd use XMLHttpRequest and its responseXML property instead, which will work in all major browsers. Example:
function readLevel(xmlDoc) {
alert(xmlDoc.documentElement.tagName);
// Your existing code goes here
};
var createXmlHttpRequest = (function() {
var factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
for (var i = 0, len = factories.length; i < len; ++i) {
try {
if ( factories[i]() ) return factories[i];
} catch (e) {}
}
})();
var xmlHttp = createXmlHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
readLevel(xmlHttp.responseXML);
}
};
xmlHttp.open("GET", "levels/test.xml", true);
xmlHttp.send(null);
According to SitePoint, all the arguments are required in createDocument. Maybe the falsy values are tripping you up.