最近, 搭建好了一个基于 SOAP 的 webService 服务器. 结果, 使用 JavaScript 访问 WebService 遇到了跨域的问题!
这个是测试 html
<script>var xhr = new XMLHttpRequest();function sendMsg(){ var name = document.getElementById('name').value; // 服务的地址 var wsUrl = 'https://webservice.webxml.com.cn/WebServices/WeatherWS.asmx'; // 请求体 var soap = ''+' '; // 打开连接 xhr.open('POST',wsUrl,true); // 重新设置请求头 xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8"); xhr.setRequestHeader("SOAPAction","https://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>
浏览器按下 F12 以后:
出现
OPTIONS https://webservice.webxml.com.cn/WebServices/WeatherWS.asmx 403 (Forbidden) OPTIONS https://webservice.webxml.com.cn/WebServices/WeatherWS.asmx No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://127.0.0.1:8020' is therefore not allowed access. XMLHttpRequest cannot load https://webservice.webxml.com.cn/WebServices/WeatherWS.asmx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://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 的跨平台, 表示出极大的看好!
来源: http://www.92to.com/bangong/2018/08-29/34047047.html