使用ajax向下拉列表添加值时出现问题

时间:2015-04-30 07:02:21

标签: javascript jquery ajax

在下面的代码中,我有一个下拉列表,我想使用ajax填充下拉值,但在我的情况下,我可以获取值,但它不会在下拉列表中绑定。

function Bind() {
    $.ajax({
        type: "POST", //HTTP method
        url: "HoardReports.aspx/BindProduct", //page/method name
        data: "{'LocationID':'" + $('#<%= ddlLocation.ClientID %>').val() + "','ProductType':'" + $('#<%= ProdValrrodType.ClientID %>').val() + "'}", //json to represent argument
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            alert(msg.d);

            var splitVal = msg.d;
            var Location = splitVal.split(';');
            var length = Location.length;
            alert(length);


            var dropDown = document.getElementById('<%=dpSourceProduct.ClientID %>');
            alert(dropDown);
            for (var i = 0; i < length; ++i) {
                alert('loop');
                var option = document.createElement("option");
                option.text = Location[i];
                alert(option.text); // i can get the values
                option.value = Location[i];
                alert(option.value);
                dropDown.options.add(option);//values are not added
            }
        }
    });

}

<editable:EditableDropDownList ID="dpSourceProduct"  runat="server" Style="width: 70%; height:29px"  EnableViewState="true" onfocus="javascript: if(this.value=='--Select--'){this.value='';}" onblur="javascript: if(this.value==''){this.value='--Select--';}"/>      

2 个答案:

答案 0 :(得分:0)

更改

var dropDown = document.getElementById('<%=dpSourceProduct.CLientID%>');

var dropDown = document.getElementById('dpSourceProduct');

JsFiddle

答案 1 :(得分:0)

使用此:

dropDown.appendChild(option);

像:

function Bind() {

    $.ajax({
        type: "POST", //HTTP method
        url: "HoardReports.aspx/BindProduct", //page/method name
        data: "{'LocationID':'" + $('#<%= ddlLocation.ClientID %>').val() + "','ProductType':'" + $('#<%= ProdValrrodType.ClientID %>').val() + "'}", //json to represent argument
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            alert(msg.d);

            var splitVal = msg.d;
            var Location = splitVal.split(';');
            var length = Location.length;
            alert(length);


            var dropDown = document.getElementById('<%=dpSourceProduct.ClientID %>');
            alert(dropDown);
            for (var i = 0; i < length; ++i) {
                alert('loop');
                var option = document.createElement("option");
                option.text = Location[i];
                alert(option.text); // i can get the values
                option.value = Location[i];
                alert(option.value);
                dropDown.appendChild(option);//here
            }
        }
    });

}