如何从Javascript发送Web服务请求?

时间:2015-03-17 13:12:00

标签: javascript web-services request

我想通过Javascript将从HTML表单获取的值发送到Web服务。在下面的代码中,在检查连接状态时,我能够获得警报(' 11')(readyState = 1);即建立连接。但过了一会儿,我在响应中得到了一个带有错误代码的警报

/ 目前,我已静态输入xml中的值,因此忽略国家1和国家2变量 /

我应该在现有的脚本中更改什么?

 <html>
 <head>
 <title>SOAP JavaScript Client Test</title>
 <script type="text/javascript">
    function soap(country1, country2) {
        var xmlhttp = new XMLHttpRequest();
        alert('1');
        xmlhttp.open("POST",   "http://www.webservicex.net/Cu              r
         rencyConvertor.asmx?op=ConversionRate", true);
        alert('2'); 
        // build SOAP request
        var sr =
            '<?xml version="1.0" encoding="utf-8"?>' +
            '<soapenv:Envelope'+ 
            'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" '+
            'xmlns:web="http://www.webserviceX.NET/">' +
            '<soapenv:Header/>' +
            '<soapenv:Body>' +
            '<web:ConversionRate>' +
            '<web:FromCurrency>USD</web:FromCurrency>' +
            '<web:ToCurrency>EUR</web:ToCurrency>' +
            '</web:ConversionRate>' +
            '</soapenv:Body>' +
            '</soapenv:Envelope>';
        alert('3');
        alert(sr);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4) {
                alert(xmlhttp.responseText);
                if (xmlhttp.status == 200) {

                    alert('done use firebug to see response');
                }
            }
        }
        // Send the POST request
        alert('4');
        xmlhttp.setRequestHeader("SOAPAction", "http://www.webservicex.net/CurrencyConvertor.asmx");
        xmlhttp.setRequestHeader('Content-Type', 'text/xml');
        alert('5');
        xmlhttp.send(sr);
        alert('6');
        // send request
        // ...
        if (xmlhttp.readyState == 0) {
                alert('pass0');
               }
        else if (xmlhttp.readyState == 1) {
                alert('pass11');
               }
        else if (xmlhttp.readyState == 2) {
                alert('pass2');
               }
        else if (xmlhttp.readyState == 3) {
                alert('pass3');
               }
        else if (xmlhttp.readyState == 4) {
                alert('pass4');
               }

    return false;
    }
</script>
 </head>
<body>
<form id="abc" onsubmit="return soap(country1, country2)">
    <label>Country 1 <input type="text" id="country1"></label>
    <br><br>
    <label>Country 2 <input type="text" id="country2"></label>
    <br><br>
    <input type="submit"  value="submit">
    <br><br>
    <br><br>
    <div id="myDiv"></div>
    </form> 
   </body>
    <html>

谢谢

0 个答案:

没有答案