一、創建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,大功告成。
有不懂的地方可以問我啦。