目标:c#后台直连数据库并查询表内数据,把数据返回给前台页面
public JsonResult GetTableData()
{
//新建一个list用来保存返回给页面的数据
List<string> reslist = new List<string>();
String addstr = "";
try
{
string connectionString = "Data Source=.;Initial Catalog=databasename;User ID=sa;Password=sa;";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string query = "SELECT * FROM tablename order by id";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
//组织返回给页面的数据
//假设被查询的表有6列,我们读取每一行的每一列用英文逗号隔开添加到一个list
while (reader.Read())
{
addstr = reader[0].ToString() + ",";
addstr += reader[1].ToString() + ",";
addstr += reader[2].ToString() + ",";
addstr += reader[3].ToString() + ",";
addstr += reader[4].ToString() + ",";
addstr += reader[5].ToString();
reslist.Add(addstr);
}
reader.Close();
connection.Close();
}
catch (Exception e)
{
return Json("ERR" + e.Message);
}
//返回数据给页面
return base.Json(new { ResData = reslist }, JsonRequestBehavior.AllowGet);
}
前台页面遍历数据:
function GetData() {
$.ajax({
url="./GetTableData?",
type: "POST",
success: function (res) {
//遍历
$.each(res.returnData, function (j, n) {
console.log("当前循环次数是:"+j)
console.log("当前循环内容是:"+n)
//把n用逗号分割,便可获取每一列的内容
var Data = n.split(',');
console.log("内容获取:"+Data[0]+Data[1]+Data[2]+Data[3]+Data[4]+Data[5]);
}
}
})
}
完结!