如何在ajax中调用RESTful Web服务?

时间:2015-05-19 14:28:00

标签: ajax html5 web-services restful-authentication

我正在尝试使用Restful Web Service通过Ajax进行货币转换。在这里,我无法解析或读取由Restful webservice生成的xml文件中的数据,请查看我的代码并帮助我。

代码:

<html> 
<head> 
    <script>
        var xmlHttp
        function showCust()
        {
            // alert("function Called");

            xmlHttp = new XMLHttpRequest();
            //  alert("function Called");
            //var fromCurr = document.getElementById("name");
            var fromCurr = f1.elements[0].value;
            var toCurr = f1.elements[1].value;
            // alert("function Called");
            //alert(fromCurr + " " +toCurr);
            var url = "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=" + fromCurr + "&ToCurrency=" + toCurr;
            alert(url);
            xmlHttp.open("GET", url, true);//it will call 'CustomerDetails' servlet 
            // alert("function Called");
            xmlHttp.onreadystatechange = stateChanged;//this is userdefined method which will fired based readyState property 
            xmlHttp.send();
        }

        function stateChanged()
        {
            // alert("function Called");

            //check whether the response is completely loaded or not? 
            if (xmlHttp.readyState == 4)
            {

                var str1 = xmlHttp.responseText;
                alert(str1);
                //var myObject = eval('(' + str1 + ')');
                //var text = '{"name":"Sivarmayya","email":"smadhupada@miraclesoft.com","phone":"9000387222"}'
                var users = xml.getElementsByTagName("double");
                alert(users);
                var user = users[0];



                //var obj = JSON.parse(str1);
                //document.f1.mail.value=obj.mail; 
            }
        }
    </script> 
</head> 
<body>

    <form name="f1" > 
        From Currency:&nbsp; <input type="text" title="enter from currency"  id="name"/><br> 
        To Currency:&nbsp; <input type="text" title="enter to currency"  id="name1"/></br>
        <input type="submit" value="Go" onclick="return showCust()">
        Result:&nbsp;&nbsp;<input type="text" name="mail" /><br> 
    </form> 
</body> 

1 个答案:

答案 0 :(得分:0)

虽然您没有提供您遇到的错误,但我认为您的问题是您的浏览器阻止了CORS请求:http://en.wikipedia.org/wiki/Cross-origin_resource_sharing