【问题标题】:How to load dropdown using ajax如何使用ajax加载下拉菜单
【发布时间】:2020-02-29 09:04:27
【问题描述】:

加载下拉列表,当我在城市表中添加数据时,下拉列表将加载到页面上而不加载页面

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" 
    DataSourceID="SqlDataSource1" onchange="showhideDiv()" 
    DataTextField="Name" DataValueField="Name"></asp:DropDownList>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
    SelectCommand="SELECT [Name] FROM [City]"></asp:SqlDataSource>

<script type="text/javascript">
$(document).ready(function () {
    $('#btnAddCity').click(function () {
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: '2tabledataenterusing1page.aspx/insert_data',
            data: "{'Name':'" + document.getElementById('txtaddcity').value + "'}",

            success: function (response) {
                $('#txtaddcity').val('');
                $('#MainContent_DropDownList1').Onload();
                alert("Record Has been Saved in Database");
            },
            error: function () {
                console.log('there is some error');
            }
        });
    });
});
</script>  

【问题讨论】:

    标签: jquery asp.net ajax


    【解决方案1】:

    错误 #1

    您不想使用.click() 作为事件,因为click 会在用户点击下拉菜单时立即触发,早在他们选择新值之前。

    使用.change()


    错误 #2

    这是错误的:

    data: "{'Name':'" + document.getElementById('txtaddcity').value + "'}"
    

    它产生以下字符串:

    {'Name':'some city name'}
    

    这不是 JSON。 JSON 中没有单引号字符串,尝试在服务器端解析会失败。

    不要通过字符串连接构建 JSON。 永远。始终使用JSON.stringify()

    data: JSON.stringify({Name: document.getElementById('txtaddcity').value}),
    

    这将从 JS 对象创建有效的 JSON,并且服务器将能够成功解析它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2018-10-30
      • 2021-04-06
      • 1970-01-01
      • 2021-10-02
      • 2023-04-09
      相关资源
      最近更新 更多