使用jQuery调用ASP.NET WebService的简易教程
2024-10-14 06:50:21
鉴于使用Javascript调用Web Service配置略麻烦,所以记录一下。
1. 新建一个Web服务(WebService.asmx)
2. 取消注释
// [System.Web.Script.Services.ScriptService]
3. 在public string HelloWorld()方法前加上
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
并且需要
using System.Web.Script.Services;
4. 在web.config中加入
<system.web>
<webServices>
<protocols>
<add name="HttpSoap" />
<add name="HttpPost" />
<add name="HttpGet" />
<add name="Documentation" />
</protocols>
</webServices>
</system.web>
完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Web.Script.Services; namespace WebService
{
/// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
try
{
return "Hello World";
}
catch (Exception e)
{
File.WriteAllText(e.Message + "\r\n" + e.StackTrace, "log.txt");
throw;
}
}
}
}
客户端调用代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="generator" content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title>AJAX</title>
<script src="jquery-2.0.3.min.js" type="text/javascript">
</script>
<script>
function ajax() {
$.ajax({
type: "post",
contentType: "application/json",
url: "http://localhost/webservice.asmx/HelloWorld",
success: function(msg) {
alert(JSON.stringify(msg));
}
});
}
</script>
</head>
<body>
<form>
<input id="btn" type="button" onclick="ajax()" value="click" />
</form>
</body>
</html>
最新文章
- select与poll函数介绍
- Google Chrome浏览器各版本直接下载地址
- IE下判断IE版本的语句...[if lte IE 6]……[endif]
- CSS Layout
- MIS框架开发计划
- android ListView和GridView拖拽移位实现代码
- oracle 11g 基于磁盘的备份rman duplicate
- 1213 How Many Tables 简单的并查集问题
- Docker Compose容器编排
- 友盟统计单页面应用vue
- js一些常规操作
- TCP 远程执行CMD (解决粘包问题) 代码
- storm的一些相关文章
- Mac OS X /home 目录权限修改
- PHP/ThinkPHP5 框架集成微博登录入库流程示意
- js遇到问题汇总
- KVM 重命名虚机
- thinkPHP5 报错session_start(): No session id returned by function解决方法
- 操作EXCEL COM组件
- 零次学习(Zero-Shot Learning)入门(转)