如题,以前只试过用js调用.net开发的webservices接口。后来想是否也可以用js调用java开发的接口,通过一整天的时间研究、查资料,发现网上对js调用java接口的资料很少,没办法,只好自己瞎搞,运气不错,终于瞎碰出来了。下面是两个例子:
1.调用.net接口
Html代码:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <script type="text/javascript">
- function RequestWebService() {
- //这是我们在第一步中创建的Web服务的地址
- var URL = "http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx?op=getStationName";
- //在这处我们拼接
- var data;
- data = '<?xml version="1.0" encoding="utf-8"?>';
- datadata = data + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
- datadata = data + '<soap:Body>';
- datadata = data + '<getStationName xmlns="http://WebXml.com.cn/" >11</getStationName>';
- datadata = data + '</soap:Body>';
- datadata = data + '</soap:Envelope>';
- //创建异步对象
- var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
- xmlhttp.Open("POST", URL, false);
- xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml");
- xmlhttp.SetRequestHeader ("SOAPAction","http://WebXml.com.cn/getStationName");
- xmlhttp.Send(data);
- document.getElementById("data").innerHTML = xmlhttp.responseText;
- alert(xmlhttp.responseText);
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <input id="One" type="button" value="JsCallWebService" onclick="RequestWebService()" />
- </div>
- <div id="data">
- </div>
- </form>
- </body>
- </html>
2.调用java接口
Html代码:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <script type="text/javascript">
- function RequestWebService() {
- //这是我们在第一步中创建的Web服务的地址,这个地址取自wsdl接口描述信息中的service节点中location值
- var URL = "http://localhost:8080/test/services/demo";
- //在这处我们拼接
- var data;
- data = '<?xml version="1.0" encoding="utf-8"?>';
- datadata = data + '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
- datadata = data + '<soap:Body>';
- //添加方法与参数
- datadata = data + '<getData><arg1>我是第一个参数</arg1><arg2>我是第二个参数</arg2></getData>';
- datadata = data + '</soap:Body>';
- datadata = data + '</soap:Envelope>';
- //创建异步对象
- var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
- xmlhttp.Open("POST", URL, false);
- xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml");
- xmlhttp.Send(data);
- document.getElementById("data").innerHTML = xmlhttp.responseText;
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <input id="One" type="button" value="JsCallWebService" onclick="RequestWebService()" />
- </div>
- <div id="data">
- </div>
- </form>
- </body>
- </html>