简体   繁体   中英

How to call RESTful Web Service in ajax?

I'm trying to use Restful Web Service for currency conversion by using Ajax. Here I'm unable to parse or read data from xml file which is generated by the Restful webservice, please do look into my code and help me out.

Code:

<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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM