一、创建webservice C#工程,WebService1.asmx内容如下
二 解决webservice 跨域问题,
1:打开web.config,
添加部分为
<system.webServer>
<!--// 解决跨域请求 by wys-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET" />
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
如下图:
2:打开WebService1.asmx
修改内容如下:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
三 发布到服务器
网上有很多教程啦,这里就不写了。
四 html 内容
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSure").click(function () {
var a = $("#a").val();
$.ajax({
type: "Post", //Post传参
url: "http://127.14.160.175:802/WebService1.asmx/Add",//服务地址
data: "{a:'"+a+"'}",//参数
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function (result) {
// 调用成功后,将获取的名字填入name文本框中。
$("#name").val(result.d);
},
error: function (e) {
window.alert(e.status);
}
})
})
})
</script>
<meta charset="utf-8" />
</head>
<body>
<div>
<input type="text" id="a" />
<input type="text" id="name" />
<input type="button" id="btnSure" value="确 定" />
</div>
</body>
</html>
结果:调用webservice的Add方法,在第一个编辑框输入2,第二个编辑框会显示4,大功告成。
有不懂的地方可以问我啦。