加载下拉列表,当我在城市表中添加数据时,下拉列表将加载到页面上,而不加载页面
<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>
错误#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,服务器将能够成功解析它。