我正在研究asp.net应用程序,我试图以JSON格式从数据库中获取数据,并使用jquery将JSON数据显示到html-ul-li标签中。我的Html页面是:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript">
//function GetCompanies() {
$(document).ready(function () {
$.ajax({
type: "POST",
url: "MobileServices.asmx/BindCategory",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
success: OnSuccess,
error: OnError
});
function OnSuccess(data) {
$.each(data, function (key, value{
$("#ulCategory").append("<li><a rel=external href=Category_News.html?ID=" + value.Category_ID + ">" + value.Category_Name + "</li>");
})
}
function OnError(data) {
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul id="ulCategory">
</ul>
</div>
</form>
</body>
</html>
我访问数据的WebService是:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using System.Configuration;
namespace MobileNewsAppication
{
/// <summary>
/// Summary description for MobileServices
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MobileServices : System.Web.Services.WebService
{
public class NewsCategory
{
public long Category_ID { get; set; }
public string Category_Name { get; set; }
public string QFlag { get; set; }
}
[WebMethod]
public string BindAllCategory()
{
DataTable dt = new DataTable();
//List<NewsCategory> details = new List<NewsCategory>();
using (SqlConnection con = new SqlConnection(Connection))
{
SqlCommand cmd = new SqlCommand("AllCategory_Select", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return JsonConvert.SerializeObject(dt);
}
}
}
}
但是ul标签没有绑定任何列表项。我认为在jquery OnSuccess方法中定义的foreach循环可能是错误的。请帮帮我。
答案 0 :(得分:2)
如果这不是一个错字,那么它会导致成功回调失败的语法错误...
function OnSuccess(data) {
// $.each(data, function (key, value{ <- this is wrong
$.each(data, function() {
$("#ulCategory").append("<li><a rel='external' href='Category_News.html?ID=" + this.Category_ID + "'>" + this.Category_Name + "</li>");
});
}
尝试使用this
内的each
代替。我还将链接属性包装在引号中。除此之外它对我来说很好看。如果这不是问题,那么将console.log(data);
作为成功回调的第一行,并检查控制台是否存在错误。