4
I use JSON data to create the <options>
of a <select>
:
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.text = item.description;
option.value = item.product;
dataList.appendChild(option);
});
But I’m finding it very ugly to have it inside the code, I built this first one to see if it worked, even because this JSON will have almost 2000 items.
So I saved my JSON in a separate file and tried to include an external file as follows:
[
{"description": "Carro 1"},
{"description": "Carro 2", "product": "4"},
{"description": "Carro 3", "product": "4"},
{"description": "Carro 4", "product": "4"},
{"description": "Carro 5", "product": "4"},
{"description": "Carro 6", "product": "4"}
]
$.getJSON("js/carros.json", function(item) {
var option = document.createElement('option');
option.text = item.description;
option.value = item.product;
dataList.appendChild(option);
});
Besides the correct way to save the file and call it, another question I have is to call the jQuery library.
I need to call her inside the Javascript that I am running the code or the fact that it is present there in HTML means that it has already been loaded?
Continuing the answers given, some questions arose regarding the algorithm.
$.getJSON('js/carros.json', function(err, data) {
if (err !== null) {
console.log('Ocorreu um erro' + err);
} else {
alert("chegou aqui!")
console.log(data);
}
});
I am using this code, and is presenting the error in the Console:
jquery-2.1.0.js:8556 Failed to load file:///C:/Users/Alexandre/Desktop/Projeto%20Colet%C3%A2nea/New/js/carros.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Checking the path to where the JSON file is, is correct.
Another question that came to me, where I fit the forEach
?
Using some lib or js only?
– BrTkCa
I am using jQuery, Select2 and Bootstrap.
– Alexandre Bonadiman Angeli
How do I edit my question?
– Alexandre Bonadiman Angeli
There is an edit button below the tags that opens here Alexandre
– BrTkCa
I don’t understand why he says it’s not compatible, the way is right.
– Alexandre Bonadiman Angeli
You should be using a local server, such as Wamp or Xampp. So this with the error Cross origin.
– NoobSaibot
I understand, but do I need to use a local server for any algorithm? I mean, the idea of the program I’m working on is to be small! It doesn’t make sense to put a Wamp just to generate good programming practice.. At least that’s what I think.
– Alexandre Bonadiman Angeli