【问题标题】:jQuery ajax not connect web service .net (asmx)jQuery ajax 未连接 Web 服务 .net (asmx)
【发布时间】:2017-05-27 04:24:17
【问题描述】:

我将 javascript ajax 连接到 webservice asmx 但无法正常工作。 我测试从 aspx 连接到 web 服务它工作。

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" language="javascript">
        $(function () {
            $('#btnCallService').click(function () {
                $.ajax({
                    type: 'POST',
                    url: 'http://xxxxxxxx/ws/webservice.asmx/HelloWorld',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (response) {
                        $('#lblData').html(JSON.stringify(response));
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
        });
    </script>
</head>
<body>
  <input type="button" id="btnCallService" value="GetEmployeeDetail" />
  <label id="lblData"></label>
</body>
</html>

点击按钮后

enter image description here

【问题讨论】:

    标签: javascript jquery asp.net ajax web-services


    【解决方案1】:

    将以下代码放入您的 global.asax 文件中,并在“Application_BeginRequest”中调用此方法

    static void EnableCrossDomain()
            {
                string origin = HttpContext.Current.Request.Headers["Origin"];
                if (string.IsNullOrEmpty(origin)) return;
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
                string method = HttpContext.Current.Request.Headers["Access-Control-Request-Method"];
                if (!string.IsNullOrEmpty(method))
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", method);
                string headers = HttpContext.Current.Request.Headers["Access-Control-Request-Headers"];
                if (!string.IsNullOrEmpty(headers))
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", headers);
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
                {
                    HttpContext.Current.Response.StatusCode = 204;
                    HttpContext.Current.Response.End();
                }
            }
    

    【讨论】:

    【解决方案2】:

    只需在您的 .asmx 中取消注释以下行即可。

    // [System.Web.Script.Services.ScriptService]
    

    【讨论】:

    • 不工作。错误显示:XMLHttpRequest 无法加载 localhost:22759/test.asmx?op=HelloWorld。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多