使用JavaScript调用WebServices服务

<%@ page language="java" pageEncoding="UTF-8"%> <script type="text/javascript"> function invokeServerFunction(){ var xmlHttp; try{ // Firefox, Safari, Opera 8.0+ xmlHttp = new XMLHttpRequest(); }catch(e){ // Internet Explorer try{ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){ alert("很遗憾, 您的浏览器不支持AJAX, 请使用其它浏览器, 如Firefox、Safari、Opera8.0+"); return false; } } } xmlHttp.onreadystatechange = function(){ if(4 == xmlHttp.readyState){ alert(xmlHttp.status); if(200 == xmlHttp.status){ //document.writeln("Web服务所返回的结果为:" + xmlHttp.responseText); document.getElementById("result").innerHTML = xmlHttp.responseText; } } } 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: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>'; //这里的<sayHello>标签,对应的是客户端所要调用的服务端的方法 data = data + '<sayHello xmlns="http://www.jadyer.com/XFireDemo">'; //这里的<str>标签,对应的是传递给sayHello()方法的参数 data = data + '<str>Jadyer22</str>'; data = data + '</sayHello>'; data = data + '</soap:Body>'; data = data + '</soap:Envelope>'; //这是URL,即访问的地址,其格式为http://IP:端口/服务端项目/services/服务端提供的服务对外开放的名字 var url = "http://127.0.0.1:8088/XFire_demo/services/XFireServer"; xmlHttp.open("POST", url, true); xmlHttp.setRequestHeader ("Content-Type","text/xml; charset=UTF-8"); //这里的第二个参数,是服务端在services.xml中指定的<namespace>加上所要调用的sayHello()方法名 xmlHttp.setRequestHeader ("SOAPAction","http://www.jadyer.com/XFireDemo/sayHello"); xmlHttp.send(data); } </script> <input type="button" value="viewResult" onclick="invokeServerFunction()" /> <br/> <br/> Web服务所返回的结果为:<span id="result"></span>

你可能感兴趣的:(JavaScript,XMLhttpREquest,SOAP,firefox,Safari)