使用Ajax从后台获取数据,然后绑定到前台的select控件

时间:2022-05-22 10:15:14

有一个方案表:PlanID,PlanName两个字段,现在需要在页面加载的时候通过ajax从后台获取服务器数据然后绑定到select控件

前台JS代码:

<script type="text/javascript">
    $(document).ready(function () {
        var modelid = document.getElementById("<%=hidModelID.ClientID %>").value;
        var oldplanid = document.getElementById("<%=hidOldPlanID.ClientID %>").value;
        var para = "{'modelid':'" + modelid + "'" + "}"; //拼成json格式的字符串
        //或者这样写:
        //                var para = "{num1:'" + number1 + "'"+"," + "num2:'" + number2 + "'}";
        $.ajax({
            type: "POST",
            url: "TerminalSaleedRegisterEdit.aspx/GetFavourPlan",
            data: para,
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (msg) {
                var obj = eval("(" + msg.d + ")");
                var htm = "";
                for (i = 0; i < obj.plans.length; i++) {
                    htm = htm + "<option value='" + obj.plans[i].planid + "'>" + obj.plans[i].planname + "</option>";
                }
                $("#sltPlanID").html(htm);
                document.getElementById("sltPlanID").value = oldplanid;
            },
            error: function (e) { alert(e.message); }
        });
    });
    function ChangePlan() {
        var newplanid = document.getElementById("<%=hidNewPlanID.ClientID %>");
        newplanid.value = document.getElementById("sltPlanID").value;
    }
</script>

 

select控件:

<tr>
            <td class="title1">优惠方案</td>
            <td><select class="select" id="sltPlanID" style="width:100%;" onchange="ChangePlan()"></select></td> 

</tr>

 

后台代码:

       [WebMethod]
        public static string GetFavourPlan(string modelid)
        {
            List<FavourPlan> listPlan = new FavourPlanLogic().GetEntitys("ModelID='" + modelid + "'");
            string retStr="{'plans':[";
            for (int i = 0; i < listPlan.Count; i++)
            {
                retStr += "{'planid':'" + listPlan[i].ID + "','planname':'" + listPlan[i].PlanName + "'},";
            }
            retStr = retStr.Substring(0, retStr.Length - 1);
            retStr += "]}";
            return retStr;
        }

返回到前台的是一个数组类型的JSON字符串,例如:

{'plans':[{'planid':'11001','planname':'优惠方案1'},{'planid':'11002','planname':'优惠方案2'}]}