注意,使用ajax調用webservice時,盡量使用ie瀏覽器,如果使用chrome或者是firefox瀏覽器,很可能會出現以下異常
2013-6-1 11:10:02 com.sun.xml.internal.ws.transport.http.server.WSHttpHandler handleExchange警告: Cannot handle HTTP method: OPTIONS
1、伺服器端代碼的書寫(可以參考使用jdk調用webservice中的代碼,兩者是基本相同的)
2、ajax_webservice.html
<html><head><title>通過ajax調用WebService服務</title><script> function getXhr(){var xhr = null;if(window.XMLHttpRequest){//非ie瀏覽器xhr = new XMLHttpRequest();}else{//ie瀏覽器xhr = new ActiveXObject('Microsoft.XMLHttp');}return xhr;} var xhr =getXhr();function sendMsg(){var name = document.getElementById('name').value;//服務的地址var wsUrl = 'http://127.0.0.1:6790/hello';//請求體 var soap= '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://webservice.njupt.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){//alert('調用Webservice成功了');var ret = xhr.responseXML;var msg = ret.getElementsByTagName('return')[0];document.getElementById('showInfo').innerHTML = msg.text;//alert(msg.text);}}}</script></head><body><input type="button" value="發送SOAP請求" onclick="sendMsg();"><input type="text" id="name"><div id="showInfo"></div></body></html>