Skip to content

如何通过 jQuery 调用 WebService?

🏷️ jQuery

定义了一个 Hello.asmx 文件,代码如下:

cs
using System.Web.Services;

namespace FirstWebService
{
    /// <summary>
    /// Hello 的摘要说明
    /// </summary>
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
    [System.Web.Script.Services.ScriptService]
    public class Hello : System.Web.Services.WebService
    {

        public string SayHello(string name)
        {
            return string.Format("Hello, {0}!", name);
        }
    }
}

html 页面代码如下:

点击查看代码
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
	<meta charset="utf-8" />
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    Say Hello to <input type="text" id="name" /> <input type="button" id="btnSayHello" value="Say" />
    <br />
    <label id="result"></label>
    <script>
        $(function () {
            $("#btnSayHello").click(function () {
                var d = {};
                d.name = $("#name").val();
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Hello.asmx/SayHello",
                    data: JSON.stringify(d),
                    dataType: "json",
                    success: function (result) {
                        $("#result").html(result.d);
                    }
                });
            });

        });
    </script>
</body>
</html>

注意

特性默认是注释掉的,一定要取消注释,否则通过 js 访问会返回 500 错误。