在 HTML 页面上调用简单的 asmx 网络服务方法

Calling simple asmx webservice method on HTML page

我想请求您帮助解决我在 HTML 页面上调用 ASP.NET webservice 方法的问题。代码非常简单,但通常不起作用。一般来说,因为我找到了一个浏览器 - IE 11,在 上它工作正常。在所有其他浏览器上,网络服务响应为空(XMLHttpRequest 对象的状态 属性 returns 0 而不是 200)。有趣的是,如果我直接把方法地址(http://www.rpdp.hostingasp.pl/RPDPWebService.asmx/HelloWorld)放到任何浏览器的URL栏,结果都是正确的:Hello World .结论 - webservice 运行良好,但我无法在 JS 代码中正确调用它的方法。 我已经阅读了关于此事的多个讨论,并假设问题与安全问题和跨域资源共享有关。考虑到所有这些,我尝试了很多技巧,但没有成功。我对这件事很陌生,如果有人能告诉我要在下面的代码中更改什么以使其在每个浏览器上都能工作,我将不胜感激。

亲切的问候,

Piotrek

P.S。我在外部托管 ASP.NET 网络服务器上发布我的网络服务,因此我无法更改它的(服务器)设置。

ASP.NET 网络服务:

namespace RPDP
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class RPDPWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

在 web.config.xml 文件中,我添加了以下标签(第一个 in ,第二个 - in ):

<webServices>
    <protocols>
        <add name="HttpSoap"/>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
    </protocols>
</webServices>

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Headers" value="accept, content-type" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
    </customHeaders>
</httpProtocol>

HTML 页面,我在该页面上调用我的网络服务方法:

<html>
<head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>  
  <script>
    function go()
    {   
        var req = new XMLHttpRequest();
        req.open("GET", "http://www.rpdp.hostingasp.pl/RPDPWebService.asmx/HelloWorld", true);

        req.onreadystatechange = function(){
            if ( req.readyState == 4) {
                if ( req.status >= 200 && req.status < 300 ||req.status == 304 ) {      
                    var returnData = req.responseText;
                    alert('Success! Returned data: ' + returnData);
                } else {
                    alert("Error; request.status = " + req.status);
                }
                req = null;
            };
        }

        req.send();
    }
</script>
</head>
<body onload="go();"></body>
</html>

查看以下博文:https://zqzhang.github.io/blog/2016/04/18/why-use-onload-in-cross-domain-ajax.html

建议在执行跨域Ajax请求时使用onload代替onreadystatechange

问题是 Access-Control-Allow-Origin 被定义了两次。