此系列使用asp.net构建前后端分离的博客网站。
创建一个asp.net项目
我们这里使用的是空模板,把https配置去掉(安全先不配置)
构建webapi接口有很多方法,在这里我们选择最简单的2种方式进行搭建。
1.webform
创建一个webform
打开窗体的服务器逻辑代码文件
添加如下方法
【注意:其方法必须添加webmethod特性,并设置为静态的】
[webmethod] public static string sayhello() { return "hello,asp.net"; }
导入jquery,之后将使用ajax请求后端服务器
在这里我使用nuget安装
编写前端页面通过ajax请求
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>首页</title> 6 </head> 7 <body> 8 <button id="click">点我</button> 9 </body> 10 </html> 11 12 <script src="scripts/jquery-3.4.1.min.js"></script> 13 <script type="text/javascript"> 14 15 //入口 16 $(document).ready(function () { 17 18 //绑定事件 19 $('#click').click(function () { 20 //ajax 21 $.ajax({ 22 url: "home.aspx/sayhello", 23 type: "post", 24 contenttype: 'application/json; charset=utf-8', 25 datatype: "json", 26 success: function (res) { 27 28 alert(res.d); 29 }, 30 error: function () { 31 alert('请求失败'); 32 } 33 }); 34 }); 35 }); 36 </script>
在浏览器中我们看到,已经取得了后端的数据
2.使用一般处理程序
创建一个一般处理程序
黄山市民网:https://www.huangshanshimin.com/