關於JavaScript 訪問基於SOAP的WebService跨域問題
最近,搭建好了一個基於SOAP的WebService服務器。結果,使用JavaScript訪問WebService遇到了跨域的問題!
首先,聲明代碼中的WebService不是本人搭建,由於本人的服務器地址不方便公開。
這個是測試HTML
<html> <meta charset="utf-8" /> <head> <title>通過ajax調用WebService服務</title> <script> var xhr = new XMLHttpRequest(); function sendMsg(){ var name = document.getElementById('name').value; //服務的地址 var wsUrl = 'http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx'; //請求體 var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.itcast.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' + ' <soapenv:Body><getRegionCountry xmlns="http://WebXml.com.cn/" /></soapenv:Body> </soapenv:Envelope>'; //打開連接 xhr.open('POST',wsUrl,true); //重新設置請求頭 xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8"); xhr.setRequestHeader("SOAPAction","http://WebXml.com.cn/getRegionCountry"); //設置回調函數 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>
瀏覽器按下F12以后:
出現
OPTIONS http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx 403 (Forbidden)
OPTIONS http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.
XMLHttpRequest cannot load http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.
目前,看網上都是通過JSONP,即src服務器端JS,然后通過回調函數傳遞數據。
但是,這個得有個前提:服務器端得配合你啊,假如,你與服務器端不是一伙人,那么協調是個問題啊!
另外,對於服務器端來講,這種做法也不安全哇!
對於JavaScript 的同源策略,確實很好的提高了安全性!但是,也限制了移動端開發純HTML5+JS的APP!
目前,我已經放棄使用JavaScript 訪問 WebService了,我使用純HTML5開發移動APP的做法,也值得商榷!
保險的做法是,HTML5+JS做界面,原生語言做后端!
那么,我看不出HTML5+JS 比 Android的XML, WP的XLAM好了很多。。。
此外,我對於Qt的跨平台,表示出極大的看好!
希望,能有個大神指點我一下JavaScript 跨域問題,既保證客服端的便捷,也保證服務器端的安全!
2014-12-19