使用JQuery使用JSON数据填充下拉列表

时间:2018-01-11 14:37:30

标签: c# jquery json ajax drop-down-menu

正如上面的标题所说,我目前正在尝试使用JQuery填充带有JSON数据的下拉列表,我尝试调整一个示例并在下面出现了这个代码,但它只是用'Please Select'填充列表。任何建议都将非常感谢。

<script>
    //change module run based on module code/name
    $("#MainContent_ddlModuleCode").change(function () {

        $.ajax({
            type: "POST",
            url: "Default.aspx/GetRegJSON",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                var jsonReg = $.parseJSON(data.d);

                //$('#MainContent_ddlModuleRun').empty().append($('<option></option>').val('').html(''));
                $('#MainContent_ddlModuleRun').empty().append($('<option selected="Seleced" value ="0">Please Select</option>'));

                //Loop through
                var matchVal = $("#MainContent_ddlModuleCode option:selected").val();
                jsonReg.ModuleVersions.filter(function (modulecode) {
                    if (modulecode.ModuleRuns != null) {                            
                        $(modulecode.ModuleRuns).each(function (i) {
                            $("#MainContent_ddlModuleRun").append($('<option></option>').val(modulecode.moduleRuns[i].moduleRunUrn).html(modulecode.moduleRuns[i].runName + ' ' + modulecode.moduleRuns[i].runStartDate));
                            $("#MainContent_ddlModuleRun").append('<option>Hello</option>').val('Hello').html('Hello');
                        });
                    }
                });
            },
            error: function () {
                alert('Error: could not retrieve module information.');
            }
        });
    });
</script>

Json数据如下:

{
  "AgendaUrn": 21111518,
  "ModuleCredit": 20,
  "ModuleLevel": "3",
  "ModuleRuns": null,
  "moduleCode": "UZZTW-20-3",
  "moduleName": "MATHS"
},
{
  "AgendaUrn": 20437486,
  "ModuleCredit": 20,
  "ModuleLevel": "3",
  "ModuleRuns": [
    {
      "AgendaUrn": 20437486,
      "SiteUrn": 5,
      "moduleRunUrn": 2211291,
      "runName": "17FEB/1",
      "runStartDate": "2018-02-26T00:00:00"
    },
    {
      "AgendaUrn": 20437486,
      "SiteUrn": 5,
      "moduleRunUrn": 2200398,
      "runName": "17MAY/1",
      "runStartDate": "2018-05-14T00:00:00"
    }
  ],
  "moduleCode": "UZ3WR1-20-3",
  "moduleName": "BIOLOGY"
},

0 个答案:

没有答案