我是Ajax
的新手。在使用HTML table
成功在数据库中插入数据后,我尝试更新Ajax
,而不是使用window.location.reload()
加载整个表单。
插入方法
[WebMethod]
public static void SaveUser(Employee objEmployee) //Employee is the class
{
//My Code for insert
}
这可以在数据成功插入时正常工作。Ajax
插入定义如下
更新方法
public static void GetData() //Tried using datatable as return type nothing happened
{
//var dt = new DataTable();
using (var con = new SqlConnection(Constr))
{
const string query = "select * from TblUser";
using (var cmd = new SqlCommand(query, con))
{
using (var sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (TableData)
{
sda.Fill(TableData);
//return TableData;
}
}
}
}
}
按钮保存我的ajax
脚本就像这样
<script type="text/javascript">
$(function () {
$("#btnSave").click(function () {
alert("TESST");
var user = {};
user.FName = $("#FirstName").val();
user.LName = $("#Surname").val();
user.MName = $("#MiddleName").val();
// Some others are also there
user.CreatedDateTime = new Date();
user.ModifiedDateTime = new Date();
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{objEmployee: ' + JSON.stringify(user) + '}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
alert("User has been added successfully.");
//Another Ajax to update the grid
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetData",
data: "{}",
dataType: "json",
success: function () {
},
error: function () {
alert("Error while Showing update data");
}
});
},
error: function () {
alert("Error while inserting data");
}
});
return false;
});
});
</script>
我已经像这样绑定到HTML表了
<table id="dataTables-example" role="grid">
<thead>
<tr role="row">
<th>Name</th>
<th>Email Id</th>
<th>Mobile(H)</th>
<th >Mobile(O)</th>
<th>Joining Date</th>
<th>Birth Date</th>
</tr>
</thead>
<tbody>
<% for (var data = 0; data < TableData.Rows.Count; data++)
{ %>
<tr class="gradeA odd" role="row">
<td class="sorting_1"><%=TableData.Rows[data]["FName"]%></td>
<td><%=TableData.Rows[data]["EMail"]%></td>
<td><%=TableData.Rows[data]["Telephone"]%></td>
<td><%=TableData.Rows[data]["Mobile"]%></td>
<td><%=TableData.Rows[data]["DOJ"]%></td>
<td><%=TableData.Rows[data]["DOB"]%></td>
</tr>
<% } %>
</tbody>
</table>
我的问题
- 我的更新方法在插入后调用,但我无法看到更新的数据。
- 页面刷新后,
醇>webmethod
为static
多个数据显示。
答案 0 :(得分:0)
循环接收收到的数据并将其设置到您的表格中:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetData",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#dataTables-example tbody").append("<tr><td>" + data.d[i].FName+ "
</td><td>" + data.d[i].EMail+ "</td><td>" + data.d[i].Telephone+ "
</td></tr>");
}
},
error: function () {
alert("Error while Showing update data");
}
});