I have the following ajax call but instead to show me all objects it shows me only the last object from json file. Why is this?
Ajax Call
var ajax = new XMLHttpRequest();
var data = 'data.json';
var url = 'http://localhost:8888/';
ajax.onreadystatechange = function() {
if (ajax.readyState === 4 ) {
if(ajax.status === 200){
callback(ajax.responseText);
} else if(ajax.status === 400) {
console.warn('404');
} else {
console.warn('bad' + ajax.responseText);
}
}
};
ajax.open('GET', url+data, true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
ajax.setRequestHeader('Access-Control-Allow-Origin', '*');
ajax.send(data);
JSON
{
"video": {
"mp4": "http://localhost:8888/500x.mp4",
"webm": "http://localhost:8888/500x.webm",
"title": "video1" },
"video": {
"mp4": "http://localhost:8888/dodge.mp4",
"webm": "http://localhost:8888/dodge.webm",
"title": "video2" },
"video": {
"mp4": "http://localhost:8888/500x.mp4",
"webm": "http://localhost:8888/500x.webm",
"title": "video3" }
}
Callback function where getVideoURL is my Ajax Call Function
inject : function(tabId, infos, tab){
if(doner.activated && infos.status === 'complete' && doner.filters.isYoutubeUrl(tab.url)){
doner.getVideoUrls(function(data){
chrome.tabs.executeScript(tabId,{
code : '!function(e){"use strict";console.debug("starting injection");var t=document.createElement("script");t.src=chrome.extension.getURL("scripts/injectedScript.js"),t.onload=function(){this.parentNode.removeChild(this)},(document.head||document.documentElement).appendChild(t);var o=document.getElementById("extAdd");o&&o.parentNode&&(console.log("removing",o),o.parentNode.removeChild(o));var n=document.createElement("iframe");document.getElementById("player-api").setAttribute("style","padding:0;");n.id="extAdd",n.setAttribute("style","border-style:none;-webkit-appearance:none;border:0;outline:none;"),n.className="html5-video-player el-detailpage ps-null hide-info-bar autohide-controls-aspect autohide-controls-fullscreen autominimize-progress-bar-non-aspect ad-created endscreen-created captions-created captions-loaded ytp-block-autohide paused-mode",n.setAttribute("allowfullscreen","true"),n.src=chrome.extension.getURL("iframe/iframe.html?id="+e);var d=document.getElementById("player-api");d.insertBefore(n,d.childNodes[0]);}("' + encodeURIComponent(JSON.stringify(data)) + '");',
runAt: 'document_start'
}, function(){
// get the popup and increase the watched value
chrome.storage.local.get({ 'watched' : 0 },function(item){
console.log(item);
chrome.storage.local.set({'watched':item.watched + 1});
});
console.log('injected');
});
});
}
}
Your JSON is an object, and the property video is declared three times. So the last declaration stay in the memory.
Maybe you should change your JSON structure and use an array :
[
{
"video": {
"mp4": "http://localhost:8888/500x.mp4",
"webm": "http://localhost:8888/500x.webm",
"title": "video1"
}
},
{
"video": {
"mp4": "http://localhost:8888/dodge.mp4",
"webm": "http://localhost:8888/dodge.webm",
"title": "video2"
}
},
{
"video": {
"mp4": "http://localhost:8888/500x.mp4",
"webm": "http://localhost:8888/500x.webm",
"title": "video3"
}
}
]
Related
In the image i have the block. When a username/tag is selected it should remove the fields but it just doesn't. When the else code block runs the fields exist, but it still doesnt remove anything it just stays there.
everything works except the field remover.
Thanks, for your support!
block data:
const blockData = {
"message0": "%1 %2 %3",
"args0": [
{
"type": "input_dummy"
},
{
"type": "field_dropdown",
"name": "MODE",
"options": [
["username", "USERNAME"],
["tag", "TAG"],
["avatarURL", "AVATARURL"],
["bannerURL", "BANNERURL"],
["createDM", "CREATEDM"],
["deleteDM", "DELETEDM"]
]
},
{
"type": "input_dummy",
"name": "test",
},
],
"previousStatement": null,
"nextStatement": null,
"colour": "#40BF4A",
"tooltip": "Set the timestamp of an embed.",
"helpUrl": "",
};
const stringArr = [ "AVATARURL", "DELETEDM", "CREATEDM", "BANNERURL"]
function removeInputs(exclude, block) {
for(let str of stringArr) {
if(str != exclude) if(block.getField(str)) block.removeInput(str)
}
}
Blockly.Blocks[blockName] = {
init: function() {
this.jsonInit(blockData);
},
onchange: function(ev) {
let field = ev.newValue
if(stringArr.includes(field)) {
switch(field) {
case "AVATARURL":
if(!this.getField("AVATARURL")) this.appendValueInput("AVATARURL").setCheck("Boolean").setAlign(Blockly.ALIGN_RIGHT);
removeInputs("AVATARURL", this)
break;
case "CREATEDM":
if(!this.getField("CREATEDM")) this.appendValueInput("CREATEDM").setCheck("Boolean").setAlign(Blockly.ALIGN_RIGHT);
removeInputs("CREATEDM", this)
break;
case "DELETEDM":
if(!this.getField("DELETEDM")) this.appendValueInput("DELETEDM").setCheck("Boolean").setAlign(Blockly.ALIGN_RIGHT);
removeInputs("DELETEDM", this)
break;
case "BANNERURL":
if(!this.getField("BANNERURL")) this.appendValueInput("BANNERURL").setCheck("Boolean").setAlign(Blockly.ALIGN_RIGHT);
removeInputs("BANNERURL", this)
break;
}
}
else {
if(this.getField("BANNERURL")) this.removeInput("BANNERURL")
if(this.getField("DELETEDM")) this.removeInput("DELETEDM")
if(this.getField("CREATEDM")) this.removeInput("CREATEDM")
if(this.getField("AVATARURL")) this.removeInput("AVATARURL")
}
}
};
Block image
I have a this code that fetches data from a remote server and i have placed it on mounted
var get_one = 'https://api.example.com/rb.php';
axios.get(get_one)
.then(response => {
// console.log(response.data);
var data = response.data;
this.roomsData = data;
this.room_name = response.data.room_name;
this.roomsData.room_photos = response.data.room_photos;
})
.catch(e => {
this.errors.push(e)
});
when i refresh the page and {{roomsData.room_photos}} looks like this
[ { "url": "/var/www/html/uploads/609cd3aaaaefd.jpg" }, { "url": "/var/www/html/uploads/609cd3aaa9dc2.jpg" }, { "url": "/var/www/html/uploads/609cd3aab1252.jpg" }, { "url": "/var/www/html/uploads/609cd3aab147a.jpg" }, { "url": "/var/www/html/uploads/609cd3aab0226.jpg" }, { "url": "/var/www/html/uploads/609cd3aaaf92b.jpg" }, { "url": "/var/www/html/uploads/609cd3aaec480.jpg" }, { "url": "/var/www/html/uploads/609cd3ab3a61b.jpg" }, { "url": "/var/www/html/uploads/609cd3ab432cb.jpg" }, { "url": "/var/www/html/uploads/609cd3ab00b91.jpg" }, { "url": "/var/www/html/uploads/609cd3ab02040.jpg" }, { "url": "/var/www/html/uploads/609cd3ab43f3e.jpg" }, { "url": "/var/www/html/uploads/609cd3ab3a634.jpg" }, { "url": "/var/www/html/uploads/609cd3ab4729f.jpg" }, { "url": "/var/www/html/uploads/609cd3ab47168.jpg" }, { "url": "/var/www/html/uploads/609cd3ab7af65.jpg" }, { "url": "/var/www/html/uploads/609cd3ab7dae1.jpg" }, { "url": "/var/www/html/uploads/609cd3ab8738f.jpg" }, { "url": "/var/www/html/uploads/609cd3ab86f15.jpg" }, { "url": "/var/www/html/uploads/609cd3ab8af48.jpg" }, { "url": "/var/www/html/uploads/609cd3ab95423.jpg" }, { "url": "/var/www/html/uploads/609cd3abbbdf9.jpg" }, { "url": "/var/www/html/uploads/609cd3abc455e.jpg" }, { "url": "/var/www/html/uploads/609cd3abca83e.jpg" }, { "url": "/var/www/html/uploads/609cd3abca0a0.jpg" }, { "url": "/var/www/html/uploads/609cd3abcfa7a.jpg" }, { "url": "/var/www/html/uploads/609cd3abd9d73.jpg" }, { "url": "/var/www/html/uploads/609cd3ac09a00.jpg" }, { "url": "/var/www/html/uploads/609cd3ac1382f.jpg" } ]
This is my computed function
computed: {
image_viewer_data: function () {
let vd = this.roomsData.room_photos
console.log('inside computed',vd)
let modifiedArr = vd.map(function(item){
let url_parts = item.url.split('/')
return 'https://api.example.com/uploads' + '/' + url_parts[url_parts.length - 1]
});
return modifiedArr;
}
},
which produces data in the following format when i {{image_viewer_data}}
[ "https://api.example.com/uploads/609cd3aaaaefd.jpg", "https://api.example.com/uploads/609cd3aaa9dc2.jpg", "https://api.example.com/uploads/609cd3aab1252.jpg", "https://api.example.com/uploads/609cd3aab147a.jpg", "https://api.example.com/uploads/609cd3aab0226.jpg", "https://api.example.com/uploads/609cd3aaaf92b.jpg", "https://api.example.com/uploads/609cd3aaec480.jpg", "https://api.example.com/uploads/609cd3ab3a61b.jpg", "https://api.example.com/uploads/609cd3ab432cb.jpg", "https://api.example.com/uploads/609cd3ab00b91.jpg", "https://api.example.com/uploads/609cd3ab02040.jpg", "https://api.example.com/uploads/609cd3ab43f3e.jpg", "https://api.example.com/uploads/609cd3ab3a634.jpg", "https://api.example.com/uploads/609cd3ab4729f.jpg", "https://api.example.com/uploads/609cd3ab47168.jpg", "https://api.example.com/uploads/609cd3ab7af65.jpg", "https://api.example.com/uploads/609cd3ab7dae1.jpg", "https://api.example.com/uploads/609cd3ab8738f.jpg", "https://api.example.com/uploads/609cd3ab86f15.jpg", "https://api.example.com/uploads/609cd3ab8af48.jpg", "https://api.example.com/uploads/609cd3ab95423.jpg", "https://api.example.com/uploads/609cd3abbbdf9.jpg", "https://api.example.com/uploads/609cd3abc455e.jpg", "https://api.example.com/uploads/609cd3abca83e.jpg", "https://api.example.com/uploads/609cd3abca0a0.jpg", "https://api.example.com/uploads/609cd3abcfa7a.jpg", "https://api.example.com/uploads/609cd3abd9d73.jpg", "https://api.example.com/uploads/609cd3ac09a00.jpg", "https://api.example.com/uploads/609cd3ac1382f.jpg" ]
This is how i am using my computed function
<div class="carousel-item" v-for="(value,index) in image_viewer_data" >
<img class="d-block w-100" :src="value" :id="index" >
</div>
when i refresh the page i get this errors.
[Vue warn]: Error in render: "TypeError: vd.map is not a function
and
TypeError: vd.map is not a function
Why is the code simultaneously working and failing at the same time.
that warning message means that vd is not an array , thus cannot find map() . and its working because the type of object you have is iterable so it behaved like an array.
try creating a new array instance from it using Array.from() :
let vd = [ { "url": "/var/www/html/uploads/609cd3aaaaefd.jpg" }, { "url": "/var/www/html/uploads/609cd3aaa9dc2.jpg" }, { "url": "/var/www/html/uploads/609cd3aab1252.jpg" }, { "url": "/var/www/html/uploads/609cd3aab147a.jpg" } ]
let modifiedArr = Array.from(vd).map(function(item){
let url_parts = item.url.split('/');
return 'https://api.example.com/uploads' + '/' + url_parts[url_parts.length - 1];
});
console.log(modifiedArr);
seems like the vd is not an array while you getting errors. Wondering why? The possible reason, your code is accessing the vd.map before the data loads.
So, adding a null check before accessing vd will help here. Eg:
let modifiedArr = vd?.map(item=>{
...
...
}) || [];
will be a perfect blend here.
In common format,
let modifiedArr = vd && vd.map() || []
I have an external JSON file that looks like this:
[
{
"id": "1",
"label": "2017-03-30",
"value": "1675000",
"accessories": "true"
},
{
"id": "2",
"label": "2017-04-01",
"value": "1440000",
"accessories": "true"
},
{
"id": "3",
"label": "2017-04-02",
"value": "830000",
"accessories": "false"
}
]
I can fetch the JSON using the following button and it displays in the div ID of accessories:
<button id="button2">Get Customers</button>
<h1>Brands that sell Accessories:</h1>
<div id="accessories"></div>
The JavaScript I am using is:
document.getElementById('button2').addEventListener
('click', loadData);
function loadData(e) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onload = function() {
if(this.status === 200) {
// console.log(this.responseText);
const customers = JSON.parse(this.responseText);
let output = '';
customers.forEach(function(customer) {
output += `
<ul>
<li>Company ID: ${customer.id}</li>
<li>Company label: ${customer.label}</li>
<li>Company value: ${customer.value}</li>
<li>Company Accessories: ${customer.accessories}</li>
</ul>
`;
})
document.getElementById('accessories').innerHTML = output;
}
}
xhr.send();
};
This outputs the company information in bullet points.
What I want to do next is remove the HTML by pressing the same button but I'm struggling to keep it removed.
I've tried:
function removeAcc() {
document.getElementById('accessories').innerHTML = '';
}
But it just flashes back to the same list.
Help will be very much appreciated.
you need to save the current state of your program somewhere so that you know if the "external JSON" was already loaded or not. This way you can switch the action in the eventListener like so:
document.getElementById('button2').addEventListener('click', toggleData);
function toggleData(e) {
if(hasData) {
removeAcc()
hasData = false;
} else {
loadData(e)
hasData = true;
}
}
I'm struggling to manipulating a tree object in JS, it might be simple but I can't find out.
Here is the object :
{
"100-silk": {
"url": "https://www.striiiipes.com/product-category/100-silk/"
},
"apparel": {
"url": "https://www.striiiipes.com/product-category/apparel/"
},
"ipad-accessories": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/",
"ipad-air": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-air/"
},
"ipad-mini": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-mini/"
},
"ipad-pro": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/",
"ipad-pro-12-9": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-12-9/"
},
"ipad-pro-9-7": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-9-7/"
}
}
}
I'm using a simple recursion function to get throught all childrens :
function parseCategories(a) {
if (typeof a === 'object') {
$.each(a, function (i, v) {
//if we only have a "url" object, then we're on last branch and can parse it
if (Object.keys(v).length === 1 && 'url' in v) {
//dosomething
} else { // then we need to go deeper in the tree
parseCategories(v);
}
})
}
}
I'd like to use this function to also save the breadcrumb and get an object like this :
"100-silk": {
"categories" : ["100-silk"],
"url": "https://www.striiiipes.com/product-category/100-silk/"
},
"apparel": {
"categories" : ["apparel"],
"url": "https://www.striiiipes.com/product-category/apparel/"
},
"ipad-accessories": {
"categories" : ["ipad-accessories"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/",
"ipad-air": {
"categories" : ["ipad-accessories", "ipad-air"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-air/"
},
"ipad-mini": {
"categories" : ["ipad-accessories", "ipad-mini"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-mini/"
},
"ipad-pro": {
"categories" : ["ipad-accessories", "ipad-pro"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/",
"ipad-pro-12-9": {
"categories" : ["ipad-accessories", "ipad-pro", "ipad-pro-12-9"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-12-9/"
},
"ipad-pro-9-7": {
"categories" : ["ipad-accessories", "ipad-pro", "ipad-pro-9-7"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-9-7/"
}
}
}
};
So the point is to save the full breadcrumb in each child and parent. How should I change the parsing function to get this object ? I've tried to pass also the parent in each loop but I can't manage to get exactly what I want...
I've create a jsfiddle here.
Thanks a lot for your help !
You could check the properties for nested objects and assign the category value.
It works with a check, if
object[k] is a truthy value, and
typeof object[k] === 'object', if the type is an object, and
!Array.isArray(object[k]), if the actual property is not an array, like a new added category,
then it assigns a new property category by using the category from the level before and adding the actual key to it.
function updateCategory(object) {
Object.keys(object).forEach(function (k) {
if (object[k] && typeof object[k] === 'object' && !Array.isArray(object[k])) {
object[k].category = (object.category || []).concat(k);
updateCategory(object[k]);
}
});
}
var data = { "100-silk": { url: "URL/100-silk/" }, apparel: { url: "URL/apparel/" }, "ipad-accessories": { url: "URL/ipad-accessories/", "ipad-air": { url: "URL/ipad-accessories/ipad-air/" }, "ipad-mini": { url: "URL/ipad-accessories/ipad-mini/" }, "ipad-pro": { url: "URL/ipad-accessories/ipad-pro/", "ipad-pro-12-9": { url: "URL/ipad-accessories/ipad-pro/ipad-pro-12-9/" }, "ipad-pro-9-7": { url: "URL/ipad-accessories/ipad-pro/ipad-pro-9-7/" } } } };
updateCategory(data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am trying to access the specific HTML element attribute and assign it to JSON property.
At first I get the JSON object from file and load it into settings. Then I go through the rows and create text inputs with various attributes.
Since I am using iris plugin, I am firing that right after. You can see that I am using changeElements function, where iris-id is being used (which works).
So the question is... why the color property in iris part is empty?
function startCorr(jsonFile) {
request = new XMLHttpRequest();
request.open('GET', jsonFile, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
settings = JSON.parse(request.responseText);
$.each(settings, function(key, jsonRow) {
$(sidePanel).append(createInput(key, jsonRow));
});
// iris
$('.iris').iris({
color: $(this).attr("iris-color"), // doesn't work
width: 200,
border: false,
hide: false,
change: function(event, ui) {
changeElements($(this).attr("iris-id"), ui);
}
});
} else {
console.log("Error getting JSON file");
}
};
request.send();
}
function createInput(key, jsonRow) {
input = "<label>" + jsonRow.name + "<input type='text' class='iris' id='" + jsonRow.section + "' ";
input += "iris-color='" + getColor(jsonRow.selectors[0]) + "' iris-id='" + key + "'>";
input += "</label>"
return input;
}
function getColor(selectorObject) {
return $(selectorObject.selector).css(selectorObject.style);
}
JSON
[
{
"name": "Global text",
"section": "text-global",
"input": "color",
"selectors": [
{
"selector": ".button.special",
"style": "background-color"
},
{
"selector": ".button.notSoSpecial",
"style": "color"
}
],
"areas": ["homepage", "detail", "category", "basket"]
},
{
"name": "Text on hover",
"section": "text-hover",
"input": "color",
"selectors": [
{
"selector": "#banner p",
"style": "color"
}
],
"areas": ["homepage", "detail", "category", "basket"]
}
]
When you need to access data specific to an element to pass into the options of a plugin one very common approach is to initialize the plugin within a $.each loop. Within the loop this is the current element
$('.iris').each(function() {
var $el = $(this);
$el.iris({
color: $el.attr("iris-color"),
width: 200,
border: false,
hide: false,
change: function(event, ui) {
changeElements($el.attr("iris-id"), ui);
}
});
});