zoukankan      html  css  js  c++  java
  • 使用jQuery调用ASP.NET WebService的简易教程

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



     

  • 相关阅读:
    C++字节对齐与位域
    使用GDB调试将符号表与程序分离后的可执行文件
    在windows上编译apr库
    使用samba共享文件夹,提供给window访问
    Linux常用命令
    使用VS2015编译xlslib库
    VS资源收藏<持续更新中>
    使用Visual Studio 2017 C++17模块(module)特性
    RMAN中format的参数
    C#的Process类的一些用法
  • 原文地址:https://www.cnblogs.com/maruko/p/4444149.html
Copyright © 2011-2022 走看看