通过Ajax调用WebService

本文介绍了一种通过Ajax调用WebService的方法,展示了如何在JSP页面中实现这一过程。具体包括了设置请求头、发送SOAP请求及处理响应数据等关键步骤。

此博文对应的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>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值