0

2 つのボタンを持つ非常に単純な JavaScript コードがいくつかあります。1 つ目は、Web サービス関数を呼び出すフォームを送信し、これを新しいウィンドウで開きます。

2 番目のボタンは、Web サービスからの応答テキストをページの div に入れたいことを除いて、同じことを行うことになっています。

この Web サービスは、ここで見つけた例に基づいています(下部にある zip ファイルでプロジェクトをダウンロードできます) 。

  • クラス属性が「Encosia.Samples.ASMX_CORS.WebService」である必要がある WebService.asmx マークアップにタイプミスがありました。

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>

最初のボタンをクリックすると、.xml の XML 結果を示す新しいページが開きますXMLHttpRequest。2 番目のボタンをクリックすると、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 では動作しません。

私の Web サービスで Firefox を快適に動作させる方法を誰か教えてもらえますか? Web サービスに CORS ライブラリが必要かもしれないと提案されましたが、この一般的な問題には、既に定義されたソリューションが組み込まれている必要があるようです。

4

1 に答える 1