加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过Ajax调用WebService

发布时间:2020-12-15 20:59:02 所属栏目:百科 来源:网络整理
导读:此博文对应的WebService服务端博文是 使用JDK发布一个简单的WebService 。 值得注意ajax不能跨域访问。也就是访问WebService的服务必须和你项目是同一个Ip。 JSP核心代码: %@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="U

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读