鉴于使用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>

最新文章

  1. select与poll函数介绍
  2. Google Chrome浏览器各版本直接下载地址
  3. IE下判断IE版本的语句...[if lte IE 6]……[endif]
  4. CSS Layout
  5. MIS框架开发计划
  6. android ListView和GridView拖拽移位实现代码
  7. oracle 11g 基于磁盘的备份rman duplicate
  8. 1213 How Many Tables 简单的并查集问题
  9. Docker Compose容器编排
  10. 友盟统计单页面应用vue
  11. js一些常规操作
  12. TCP 远程执行CMD (解决粘包问题) 代码
  13. storm的一些相关文章
  14. Mac OS X /home 目录权限修改
  15. PHP/ThinkPHP5 框架集成微博登录入库流程示意
  16. js遇到问题汇总
  17. KVM 重命名虚机
  18. thinkPHP5 报错session_start(): No session id returned by function解决方法
  19. 操作EXCEL COM组件
  20. 零次学习(Zero-Shot Learning)入门(转)

热门文章

  1. android最快的模拟器
  2. OO ALV 学习参考
  3. XMPP——Smack[5]文件传输及离线消息的获取
  4. cocos2d-x Action
  5. ILSpy反编译工具的使用
  6. 传微软欲收购Xamarin:未来有望通过VS开发iOS和Android应用?
  7. 使用Go语言两三事
  8. mysqldump原理4
  9. EntityFramework小知识
  10. 【转】频点CTO张成:基于Cocos2d的MMORPG开发经验