How to load an external file in JavaScript?

I am writing a script where you can add and remove a drop-down list of languages. I got it working, but my question is is there a way to externalize part of the select tag of the code, since I would have more than 100 options and load it in JavaScript when the link is clicked. I do not want to have 100 parameter tags in a script. On the PHP side, I use the include statement to load a list of parameters.

That is where my problem is.

$(function() { var scntDiv = $('#container'); var i = $('#container p').size() + 1; $('#addScnt').live('click', function() { $('<p><select>I DONT WANT TO HAVE 100 OPTION TAGS HERE</select></p>').appendTo(scntDiv); i++; return false; }); }); 

here is my code that works with multiple parameter tags in a script.

Full code .

+5
source share
3 answers

You can put all your data in a Json file, for example below (for example):

 {"student": [ { "id": "1", "name": "Person1" }, { "id": "2", "name": "Person2" }, { "id": "3", "name": "Person3" } ]} 

Now click the Run button.

  $('#addScnt').on('click', function() { //get a reference to the select element $('<p><select id="test"></select></p>').appendTo(scntDiv); var $select = $('#test`enter code here`');</code> //request the JSON data and parse into the select element $.getJSON('student.JSON', function(data){ //clear the current content of the select $select.html(''); //iterate over the data and append a select option $.each(data.student, function(key, val){ $select.append('<option id="' + val.id + '">' + val.name + '</option>'); }) }); }); 
+2
source

You can store your languages ​​as objects. This can be either a static file or a dynamically generated response. Then you can use it to create dynamic parameters:

MyLanguages.json

 [ { 'Name': 'English', 'Sign': 'EN' }, { 'Name': 'Spanish', 'Sign': 'ES' }, { 'Name': 'Russian', 'Sign': 'RU' } ] 

Your page :

 $.ajax({ url: './MyLanguages.json', dataType: 'json' }).done(function(data) { var $select = $("select"); $(data).each(function() { $("<option/>").text(this.Name).val(this.Sign).appendTo($select); }); }); 
+4
source

You can put the parameters in a JSON file and load them using an AJAX (http) request.

+3
source

Source: https://habr.com/ru/post/1236140/


All Articles