0

我有一些非常简单的带有两个按钮的 javascript 代码。第一个提交一个调用 Web 服务函数的表单并在新窗口中打开它。

第二个按钮应该做同样的事情,除了我想将来自 Web 服务的响应文本放入页面上的 div 中。

Web 服务来自我在此处找到的示例(您可以在底部以 zip 文件的形式下载该项目。

  • WebService.asmx 标记中有错字,其中 Class 属性应为“Encosia.Samples.ASMX_CORS.WebService”。

Web 服务允许所有来源<add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" />,因此跨站点脚本不应该有问题。

JavaScript 代码注意:本地主机名是我运行 Web 服务项目时由 Visual Studio 生成的

<head>
   <title>Test Web Service Using JavaScript</title>
</head>

<body>
    <form action='http://localhost:53276/WebService.asmx/HelloWorld' method="post" target="_blank">
        <input type="submit" value="This Works" class="button">
        <label> This opens a new window with the result of the web service call</label>
    </form>

    <input type='submit' id='btnTest' name='btnTest' value="This Doesn't" onclick="WebRequestTest();" >
    <label> This should fill the div with the result of the web service call</label>
     <div id="MyDiv"></div>


</body></html>

<script language="javascript">

    function WebRequestTest() {
        function handler() {
            //fires when ready state changes
            if (this.readyState == 4 ){ //&& request.responseText != '') {
                var response = request.responseText;
                document.getElementById('MyDiv').innerHTML = response;
                return;
            } 
        }

        var request = new XMLHttpRequest();
        request.onreadystatechange = handler;
        request.withCredentials = true;
        request.open('POST', 'http://localhost:53276/WebService.asmx/HelloWorld', true); //third optional argument: async (default true)
        request.send();
    }

</script>

当我单击第一个按钮时,会打开一个新页面,其中显示XMLHttpRequest. 当我单击第二个按钮时,HttpFox 告诉我我有一个:

NS_ERROR_DOM_BAD_URI 错误

结果只是一个空字符串。

因此,我也尝试过jQuery同样的结果:

function WebRequestTest2(){
    $.ajax({
        type: "GET",
        url: "http://localhost:53276/WebService.asmx/HelloWorld",
        dataType: "xml",
        success: function(xml) {
            var myString = $(xml).find('string').text();
    }
    });
}

雪上加霜的是,上面的 JavaScript 代码在 IE 8 中运行良好,但在我的目标浏览器 Firefox 17 中运行良好。

谁能告诉我如何让 Firefox 与我的网络服务配合得很好?有人建议我在我的 Web 服务中可能需要一个 CORS 库,但这个常见的问题似乎必须内置一个已经定义的解决方案。

4

1 回答 1

0

我通过使用以下示例的 WebAPI CORS 功能解决了我的问题:http ://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

此外,我需要覆盖 Firefox 发送的源,因为它在本地加载文件时为空。我使用 HttpFox 来做到这一点。

于 2013-07-17T20:53:37.460 回答