使用Web服务填充Jquery数据表
本文关键字:Jquery 数据表 填充 服务 Web 使用 | 更新日期: 2023-09-27 18:21:44
我在Asp.net
中创建了一个Web服务,它返回以下
<string xmlns="http://tempuri.org/">[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd@yahoo.com","UserId":"11"}]
现在我想在Jquery
Datatable
中填充该数据
这是HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Birthday</th>
<th>Phone</th>
<th>Email</th>
<th>UserId</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Birthday</th>
<th>Phone</th>
<th>Email</th>
<th>UserId</th>
</tr>
</tfoot>
</table>
Jquery
$.ajax({
type: 'POST',
url: 'ws.asmx/ContactsList',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(data.d);
$('#example').dataTable({
"aaData": data.d,
"aoColumns": [
{
"mDataProp": "Id"
}, {
"mDataProp": "FirstName"
}, {
"mDataProp": "LastName"
}, {
"mDataProp": "Birthday"
}, {
"mDataProp": "Phone"
}, {
"mDataProp": "Email"
}, {
"mDataProp": "UserId"
}
]
});
}});
当console.log
被称为时,data.d
显示如下
[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd@yahoo.com","UserId":"11"}]
Web服务
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ContactsList()
{
var contacts = new List<ContactsModel>();
var conn = ConfigurationManager.ConnectionStrings["AccountsConnectionString"].ConnectionString;
using (var con = new SqlConnection(conn))
{
con.Open();
const string query = "SELECT [Id], [F_name], [L_name], [Phone], [Birthday], [Email], [User_id] FROM [Contacts]";
var cmd = new SqlCommand(query, con);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var model = new ContactsModel();
model.Id = Convert.ToInt32(reader["Id"].ToString());
model.FirstName = reader["F_name"].ToString();
model.LastName = reader["L_name"].ToString();
model.Birthday = reader["Birthday"].ToString();
model.Email = reader["Email"].ToString();
model.UserId = reader["User_id"].ToString();
contacts.Add(model);
}
}
return new JavaScriptSerializer().Serialize(contacts);
}
错误
Request Unknown parameter 'Id' for Row 0
似乎web服务返回的数据被解释为字符串。尝试使用JSON.parse(data.d)
http://plnkr.co/edit/JGzCNT6Zg73xtFwAUuOx?p=preview
$(document).ready(function() {
var data = {
d : '[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd@yahoo.com","UserId":"11"}]'
};
$('#example').dataTable({
"aaData": JSON.parse(data.d),
"aoColumns": [
{
"mDataProp": "Id"
}, {
"mDataProp": "FirstName"
}, {
"mDataProp": "LastName"
}, {
"mDataProp": "Birthday"
}, {
"mDataProp": "Phone"
}, {
"mDataProp": "Email"
}, {
"mDataProp": "UserId"
}
]
});
} );