jquery用ajax调用webservice

前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery/jquery-2.0.3.min.js"></script>
</head>
<body>
<script type="application/javascript">
    $(function () {
        var url = "http://www.air.com/test.asmx/UserLogin";
        $.ajax({
            type: "GET", 
            url: url, 
            data: {userName: 'air', userPwd: '123'}, 
            dataType: "html",
            success: function (s) {
                alert(s)
                var jsonstr=s.replace(/<\/?.+?>/g,"");
                var json =$.parseJSON(jsonstr);
                alert(json.user.id);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(errorThrown);
            },
        });
    })
</script>
</body>
</html>

后端代码:

    /// <summary>
    /// test 的摘要说明
    /// </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 test : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet=true)]
        public string UserLogin(string userName, string userPwd)
        {
            string returnVal = "";
            returnVal = "{\"user\":{\"id\":\"201707031059\",\"name\":\"" + userName + "\",\"pwd\":\"" + userPwd + "\"}}";
            return returnVal;
        }
    }
Web.config:

<webServices>
      <protocols>
        <add name="HttpPost" />
        <add name="HttpGet" />
      </protocols>
    </webServices>
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpHandlers>
为了能在JQ里调用webservice,需要以上代码放在<system.web>和</system.web>之间

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
        <add name="Access-Control-Allow-Headers" value="x-requested-with"/>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>

为了能在JQ里跨域,需要以上代码放在<system.webServer>和</system.webServer>之间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值