1.结果展示
2.数据库部分
3.工程文件
4. 代码部分
(1)WebService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using Newtonsoft.Json;
using System.Web;
using System.Web.Services;
///<summary>
///WebService 的摘要说明
///</summary>
[WebService(Namespace="http://tempuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public classWebService : System.Web.Services.WebService{
string constr="DataSource=USER-20161130JY\\SQLEXPRESS;Initial Catalog=library;IntegratedSecurity=True";
SqlDataAdapter adapter;
DataSet set=newDataSet();
DataTable table;
public WebService() {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public stringHelloWorld() {
return "Hello World";
}
[WebMethod]
public stringgetlist()
{
adapter=newSqlDataAdapter("select * from books", constr);
adapter.Fill(set, "library");
SqlCommandBuilder builder=newSqlCommandBuilder();
table=set.Tables["library"];
string jsonstr=JsonConvert.SerializeObject(table);
return jsonstr;
}
}
(2)Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript"src=jquery-3.3.1.min.js></script>
<style type="text/css">
table
{
margin:0pxauto;
}
</style>
<link href="bootstrap.css"rel="stylesheet" type="text/css" />
</head>
<body>
<p id="p1">
</p>
<script type="text/javascript">
msg="";
//从后台获取图书数据,格式为XML字符串格式
function getbook(){
$.ajax({
url:"WebService.asmx/getlist", //WebService.asmx中的getlist方法
type:"post",
dataType:"text",
async:false,
success:function (dataInfo) {
msg=dataInfo.toString(); //msg得到返回的数据
},
});
}
getbook();
//字符串转化为XML对象的函数
function createXml(str) {
if (document.all) {
var xmlDom=newActiveXObject("Microsoft.XMLDOM")
xmlDom.loadXML(str)
returnxmlDom
}
else
return new DOMParser().parseFromString(str,"text/xml")
}
var xml=createXml(msg);
//获取XML对象中json字符串的部分
var string=$(xml).find("string").text();
//json字符串转json对象
var json=JSON.parse(string);
//输出table表格
var elems="<tableclass='table table-hover table-dark table-striped' ><thclass='text-center'>编号</th><thclass='text-center'>图片</th><thclass='text-center'>书名</th><thclass='text-center'>作者</th><thclass='text-center'>ISBN</th>";
for (variinjson) {
elems+="<tr>";
elems+="<td class='text-center'>"+json[i].编号+"</td>"+"<td class='text-center'>"+"<img src='"+json[i].图片地址+"' />"+"</td>"+"<td class='text-center'>"+json[i].书名+"</td>"+"<tdclass='text-center'>"+json[i].作者+"</td>"+"<tdclass='text-center'>"+json[i].ISBN+"</td>";
elems+="</tr>";
}
elems+="</table>";
document.write(elems);
</script>
</body>
</html>