使用ajax调用webservice

来源:互联网 发布:淘宝怎样优化关键词 编辑:程序博客网 时间:2024/05/22 05:21

使用ajax调用webservice时,尽量使用ie浏览器,如果使用chrome或者是firefox浏览器,很可能会出现异常

 

服务器端代码的书写(可以参考使用jdk调用webservice中的代码,两者是基本相同的)

 

  1. <html> 
  2.     <head> 
  3.         <title>通过ajax调用WebService服务</title> 
  4.         <script> 
  5.              function getXhr(){ 
  6.                 var xhr = null
  7.                 if(window.XMLHttpRequest){ 
  8.                     //非ie浏览器 
  9.                     xhr =new XMLHttpRequest(); 
  10.                 }else{ 
  11.                     //ie浏览器 
  12.                     xhr = new ActiveXObject('Microsoft.XMLHttp'); 
  13.                 } 
  14.                 return xhr; 
  15.             } 
  16.           var xhr =getXhr(); 
  17.             function sendMsg(){ 
  18.                 var name = document.getElementById('name').value; 
  19.                 //服务的地址 
  20.                 var wsUrl = 'http://127.0.0.1:6790/hello'
  21.                  
  22.                 //请求体 
  23.                  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">' 
  24.              +'<soapenv:Body><q0:sayHello><arg0>'+name+'</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>'; 
  25.                           
  26.                 //打开连接 
  27.                 xhr.open('POST',wsUrl,true); 
  28.                  
  29.                 //重新设置请求头 
  30.                 xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8"); 
  31.                  
  32.                 //设置回调函数 
  33.                 xhr.onreadystatechange =_back
  34.                  
  35.                 //发送请求 
  36.                 xhr.send(soap); 
  37.             } 
  38.              
  39.             function _back(){ 
  40.                 if(xhr.readyState == 4){ 
  41.                     if(xhr.status == 200){ 
  42.                             //alert('调用Webservice成功了'); 
  43.                             var ret =xhr.responseXML; 
  44.                             var msg =ret.getElementsByTagName('return')[0]; 
  45.                             document.getElementById('showInfo').innerHTML =msg.text; 
  46.                             //alert(msg.text); 
  47.                         } 
  48.                 } 
  49.             } 
  50.         </script> 
  51.     </head> 
  52.     <body> 
  53.             <inputtype="button"value="发送SOAP请求"onclick="sendMsg();"> 
  54.             <inputtype="text"id="name"> 
  55.             <divid="showInfo"> 
  56.             </div> 
  57.     </body> 
  58. </html> 

 

原创粉丝点击