js 调用webservice接口

1:建立的webservice工程正确运行。
a: 定义接口类
public interface IMyWebService {
public String example(String message);
}
b:实现类
public class MyWebServiceImpl implements IMyWebService {
public String example(String message) {
message = "Hello Hello Hello Hello : " + message ;
System.out.println(message);
return message;
}
}
写个测试类,利用xfire相关函数测试当前webservice是否可以正确的调用
public void XfireTest(){ //创建服务模型 (元数据)
Service mySerModel = new ObjectServiceFactory().create(IMyWebService.class);
//为XFire获得一个代理工厂对像。
XFire xfire = XFireFactory.newInstance().getXFire(); XFireProxyFactory factory = new XFireProxyFactory(xfire);
String serviceUrl ="http://10.10.1.61:8080/DwWebService/services/MyWebService"; Context.Response.ContextType="text/xml"; IMyWebService clientSerTest = null; try {
//调用它的transferFunds()方法来得到我们需要的
Web Service clientSerTest = (IMyWebService) factory.create(mySerModel, serviceUrl);
String str = clientSerTest.example("金城武!");
System.out.println(str);
}
catch (MalformedURLException e) {
System.out.println("Client.callWebService(): EXCEPTION: " + e);
}
}

调用成功后。正确打印 " Hello Hello Hello Hello : 金城武!" 2:在页面上进行js调用:
代码如下:

<html>
<title>
Call webservice with javascript and xmlhttp.
</title>
<body>
<script language="javascript">


function RequestByPostForWebService(method, value){
alert("method:" +method);
alert("value:" +value);


var data;
data = '<?xml version="1.0" encoding="utf-8"?>';
data = 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/">';
data = data + '<soap:Body>';
data = data + '<' + method + ' xmlns="http://tempuri.org/';
data = data + method + '">';
data = data + '<Name>'+value+'</Name>';
//data = data + '<Name>'+value1+'</Name>';
data = data + '</' + method + '>';
data = data + '</soap:Body>';
data = data + '</soap:Envelope>';


var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
var URL="http://10.10.1.61:8080/DwWebService/services/MyWebService";
xmlhttp.Open("POST",URL, false);
xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");
xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/example");
xmlhttp.Send(data);
alert(data);

//var result = xmlhttp.responseXML.getElementsByTagName("ns1:out")[0].firstChild.nodeValue;
var result = xmlhttp.responseText
alert(result);



}


</Script>


<input type="button" value="RequestByPostForWebService" onClick="RequestByPostForWebService('example' ,'金城武')">
</body>
</html>

posted @ 2009-06-19 15:14  Daniel_Lu  阅读(1727)  评论(0编辑  收藏  举报