.net MVC4 AJAX 调用WebService

Js 代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="../Scripts/jquery-1.8.2.min.js"></script>
    <title></title>

</head>
<body>
    <button onclick="test()"></button>
  <script type="text/javascript">
      function test() {
          settime('id');
      }
      function settime(id) {
          alert(id);
          var c = { "id": id };
          $.ajax({
              url: "/WebService.asmx/HelloWorld",
              type: "post",
              data: JSON.stringify(c),
              dataType: 'json',
              contentType: 'application/json; charset=utf-8',
              success: function (data) {
                  alert(data.d);
                  console.log(c);
                  console.log(data);
              },
              error: function (err) {
                  alert("err" + err);
                  console.info(err.responseText);
              }
          });

      }
        </script>
</body>
</html>

WebService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

namespace WebServer
{
    /// <summary>
    /// WebService 的摘要说明
    /// </summary>
    [ScriptService]
    [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]
        public string HelloWorld()
        {
            return "Hello World";
        }
         
    }
}

路由配置

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*x}", new { x = @".*\.asmx(/.*)?" });

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

猜你喜欢

转载自blog.csdn.net/zanfeng/article/details/88073055
今日推荐