使用ajax呼叫webservice
阿新 • • 發佈:2018-12-20
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); } } }