1.添加接口和类
namespace JsonpDemo
{
[ServiceContract]
public interface IEmployees
{
[WebGet(UriTemplate = "all", ResponseFormat = WebMessageFormat.Json)]
IEnumerable<Employee> GetAll();
}
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Grade { get; set; }
}
}
2.实现类
public class EmployeesService:IEmployees
{
public IEnumerable<Employee> GetAll()
{
return new List<Employee>
{
new Employee{Id="001",Name="张三",Department="开发部",Grade="G6"},
new Employee{ Id = "002", Name="李四", Department="人事部", Grade = "G7"},
new Employee{ Id = "003", Name="王五", Department="销售部", Grade = "G8"}
};
}
}
3.添加配置文件
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
<bindings>
<webHttpBinding>
<binding crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
<services>
<service name="JsonpDemo.EmployeesService">
<endpoint kind="webHttpEndpoint" address="http://127.0.0.1:2080/employees" contract="JsonpDemo.IEmployees"/>
</service>
</services>
</system.serviceModel>
</configuration>
4. 添加控制台程序
class Program
{
static void Main(string[] args)
{
using (WebServiceHost host = new WebServiceHost(typeof(EmployeesService)))
{
host.Open();
Console.Write("服务启动...");
Console.Read();
}
}
}
5.添加Web页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body
{
font-size: 12px;
text-align: center;
}
#employees
{
border: 1px solid #000000;
margin: 10px auto;
background-color: #eee;
}
#employees tr
{
line-height: 23px;
}
#employees th
{
background-color: #ccc;
color: #fff;
}
.oddRow
{
background-color: #fff;
}
</style>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax(
{
type: "get",
url: "http://127.0.0.1:2080/employees/all",
dataType: "jsonp",
success: function (employees) {
$.each(employees, function (index, value) {
var detailUrl = "detail.htm?id=" + value.Id;
var html = "<tr><td>";
html += value.Id + "</td><td>";
html += "<a href='" + detailUrl + "'>" + value.Name + "</a></td><td>";
html += value.Grade + "</td><td>";
html += value.Department + "</td></tr>";
$("#employees").append(html);
});
$("#employees tr:odd").addClass("oddRow");
}
});
});
</script>
</head>
<body>
<table id="employees" width="600px">
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Grade
</th>
<th>
Department
</th>
</tr>
</table>
</body>
</html>
源码:https://files.cnblogs.com/byzy/JsonpDemo.rar