从 json 字符串在 jqgrid 中构建下拉列表

Build dropdown in jqgrid from json string

在我的编辑表单中,我想从服务器填充一个下拉列表。我成功地 return json 字符串中的值,到客户端:

var types = 
    $.ajax({
        url: getTypesUrl,
        async: false,
        success: function (data, result) {
            if (!result)
                alert("failed to retreive harvest types.");
        }
}).responseText;

returns 这个字符串:

 [{"HarvestTypeId":1,"TypeDescription":"Elite Gain / High Elev"},{"HarvestTypeId":2,"TypeDescription":"High Gain / High Elev"},{"HarvestTypeId":3,"TypeDescription":"Med Gain / High Elev"}]

然后我使用 loadComplete 将它添加到我的 jqgrid:

$("#harvest-grid").jqGrid({
    url: gridUrl,
    styleUI: "Bootstrap",
    datatype: 'json',
    colNames: ['HarvestId', 'Harvest Year', 'Harvest Type'],
    colModel: [
            { name: "HarvestId", key: true, hidden: true },
            { name: "HarvestYear", search: true, editable: true },
            { name: "HarvestType", search: true, editable: true, edittype: "select" }
    ],
    loadonce: true,
    height: "auto",
    autowidth: true,
    rowNum: -1,
    pager: "#harvest-pager",
    editurl: editHarvestUrl,
    loadComplete: function () {
        $("#harvest-grid").setColProp('HarvestType', { editoptions: { value: types } });
    }
});

编辑表单显示 select 列表框,但将整个 json 字符串呈现为唯一选项而不是构建列表:

<select role="select" id="HarvestType" name="HarvestType" rowid="4430" size="1" class="FormElement form-control">
    <option role="option" value="[{&quot;HarvestTypeId&quot;">1,"TypeDescription":"Elite Gain / High Elev"},{"HarvestTypeId":2,"TypeDescription":"High Gain / High Elev"},{"HarvestTypeId":3,"TypeDescription":"Med Gain / High Elev"}]</option>
</select>

我建议您使用 异步 加载数据,使用 dataUrl: getTypesUrl 属性 of editoptions。您应该另外指定 buildSelect 回调,它将从 getTypesUrl 返回的数据转换为字符串

<select>
    <option value='1'>Elite Gain / High Elev</option>
    <option value='2'>High Gain / High Elev</option>
    <option value='3'>Med Gain / High Elev</option>
</select>

我建议您另外添加 prmNames: { id: "HarvestId" } 选项并删除隐藏列 "HarvestId" 以防您在从url: gridUrl.