此博文对应的WebService服务端博文是 使用JDK发布一个简单的WebService 。
值得注意ajax不能跨域访问。也就是访问WebService的服务必须和你项目是同一个Ip。
JSP核心代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/xml; charset=UTF-8">
<title>Ajax方式调用WebService</title>
<script type="text/javascript">
//IE浏览器
var xmlReq =false;
initReq();
function sendWebService(){
var v=document.getElementById('info').value;
//WebService访问地址
var wsUrl='http://localhost:1111/hello';
//请求体
var soap='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://service.cxf.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'+
' <soapenv:Body><q0:sayHello><arg0>'+v+'</arg0> </q0:sayHello></soapenv:Body></soapenv:Envelope>';
//打开请求连接
xmlReq.open("POST",wsUrl,true);
//重新设置请求头
xmlReq.setRequestHeader("Content-Type","text/xml;charset=UTF-8");
//请求回调
xmlReq.onreadystatechange=response;
//发送请求
xmlReq.send(soap);
}
//回调
function response(){
if(xmlReq.readyState==4){
if(xmlReq.status==200){
var resp=xmlReq.responseXML;
var retValue=resp.getElementsByTagName('return')[0].text;
document.getElementById('showInfo').innerHTML='服务器返回数据:'+retValue;
}
}
}
function initReq(){
// 检查使用的是否为IE浏览器
try{
// 如果JS的版本大于5
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
// 如果不是,则使用老版本的ActiveX对象
try{
// 如果使用的是IE浏览器
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
// 使用非IE浏览器
xmlReq = false;
}
}
// 如果使用的是IE非浏览器
if(!xmlReq && typeof XMLHttpRequest != 'undefined'){
xmlReq = new XMLHttpRequest();
alert("You are not using Microsoft Internet Explorer.");
}
}
</script>
</head>
<body>
<input type="text" id="info"/>
<input type="button" value="调用WebService服务" onclick="sendWebService()"/>
<br/>
<div id="showInfo">
</div>
</body>
</html>
本文介绍了一种通过Ajax调用WebService的方法,展示了如何在JSP页面中实现这一过程。具体包括了设置请求头、发送SOAP请求及处理响应数据等关键步骤。

被折叠的 条评论
为什么被折叠?



