`

二、通过Ajax调用webService服务

阅读更多

1、上一篇WebService文章介绍了基本的创建、调用WebService服务的形式,今天学习了一下通过Ajax调用WebService服务的形式,

2、首先启动一个WebService服务,代码如下:

package com.wang.webservice.service;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
@WebService
public class HelloService {
	public String sayHello( String name ){
		System.out.println(name);
		return "hello " + name;
	}	
	public static void main(String[] args) {
		Endpoint.publish("http://127.0.0.1:1234/helloservice", new HelloService());
	}
}

 3、启动后,创建一个html文件,准备通过ajax请求WebService服务,直接上代码,代码中有说明:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>通过Ajax调用webService服务</title>
</head>
<script>
	/* ActiveXObject有浏览器兼容问题 */
    var xhr = new ActiveXObject("Microsoft.XMLHTTP");
  
    function sendMsg(){
    	var name = document.getElementById("name").value;
    	
		//服务地址
		var wsUrl = "http://127.0.0.1:1234/helloservice";

		//请求体
		var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://service.webservice.wang.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
				+ '<soapenv:Body><q0:sayHello><arg0>'+ name +'</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>';

		//打开连接
		xhr.open('POST', wsUrl, true);

		//重新设置请求头
		xhr.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");

		//设置回调函数
		xhr.onreadystatechange = _back;

		//发送请求
		xhr.send(soap);
	}
	
	function _back(){
		
		if(xhr.readyState == 4){
		
			if( xhr.status == 200 ){
				/* 有浏览器兼容问题 */
				var ret = xhr.responseXML;
			 	var msg = ret.getElementsByTagName('return')[0];
			 	alert(msg);
				
			}
		}
	}
	
</script>

<body>
	<input type="button" value="发送soap请求" onclick="sendMsg()"  />
	<input  type="text" id="name"/>
</body>
</html>

此时,用IE浏览器打开这个HTML文件,基本就能看到效果了。

代码中,除了请求体外,其他的都好理解,那么这个请求体是哪来的哪儿??

4、动过myeclipse(eclipse)拦截工具获得请求体。上图:



 注:http://127.0.0.1:1234/helloservice?wsdl 上篇文章中介绍的。。



 

 

 

通过Ajax调用webService服务完毕。。。

 

  • 大小: 354.9 KB
  • 大小: 36.3 KB
  • 大小: 32.4 KB
  • 大小: 65 KB
1
1
分享到:
评论
1 楼 ocwuyou 2015-08-07  
jquery插件,还不错,有演示效果!

相关推荐

Global site tag (gtag.js) - Google Analytics