如何在JavaScript中加载外部文件?

Jos*_*eph 5 javascript jquery

我正在编写一个脚本,您可以在其中添加和删除语言下拉列表.我得到了它的工作,但我的问题是,如果有一种方法来外化代码的选择标记部分,因为我将有超过100个选项,并在单击链接时加载它在JavaScript中.我不想在脚本中有100个选项标签.在PHP方面,我使用include语句来加载我的选项列表.

这就是我的问题所在.

$(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;
    });
});
Run Code Online (Sandbox Code Playgroud)

这是我的代码,它在脚本中运行了一些选项标签.

完整代码.

bha*_*.cs 2

您可以将所有数据放入 Json 文件中,如下所示(例如):

{"student": [
  {
    "id": "1",
    "name": "Person1"
  },
  {
    "id": "2",
    "name": "Person2"
  },
  {
    "id": "3",
    "name": "Person3"
  }
]}
Run Code Online (Sandbox Code Playgroud)

现在单击实施以下内容

     $('#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>');
          })
        });
        });
Run Code Online (Sandbox Code Playgroud)