做js的ajax应用时,会遇到你需要请求的接口并不在你当前域下,此时就会出现跨域访问的问题,浏览器会禁止你请求这个接口。
此时怎么访问这个WebService的接口呢?
一个简单的办法就是在本域的服务器上,增加一个转发层,将浏览器上过来的请求接收后,通过服务器将这个请求转发到对应的WebService上,然后把返回结果再取回后,送回js的请求页面。
一般而言这个是解决跨域访问最安全与最具兼容性的办法。
下面是我写的一个php脚本,可以完成这个转发过程,仅供参考:PHP 8.5.5 PHP 8.5.5 是 PHP 8.5 分支的维护更新版本。该版本延续了“小步快跑”的迭代逻辑,通过深度错误修复、底层性能微调以及安全加固,旨在为开发者提供一个更健壮、更高效的运行环境。该版本严格遵守语义化版本规范,不包含破坏性变更。
下载立即学习“PHP免费学习笔记(深入)
”;
[php]php
getPOST();$this->getGET();if($this->msGets != '' || count($this->maGetPostData) > 0){ //存在输入数据if(count($this->msGets) > 0)$sUrl = self::URL_ROOT .'?'. $this->msGets;else$sUrl = self::URL_ROOT;header('Content-Type: text/html; charset='. self::CHARSET);echo $this->getContent($sUrl);}else{header('Content-Type: text/html; charset='. self::CHARSET);echo $this->getContent(self::URL_ROOT);}}function __destruct(){unset($maGetPostData, $msGets);}/*** 载入POST数据* @return bool* */ private function getPOST(){$handle = @fopen('php://input', 'r');$data = '';do{$data = @fread($handle, 1024);if (strlen($data) == 0) break;else$this->maGetPostData[] = $data;}while(true);fclose($handle);unset($data, $handle);return count($this->maGetPostData) >= 1;}/*** 载入GET数据* @return bool* */ private function getGET(){ www.2cto.com/*取得GET内容*/ if (count($_GET) > 0){$aTmp = array();foreach ($_GET as $sKey => $sVal)$aTmp[] = $sKey .'='. urlencode($sVal);$this->msGets = implode('&', $aTmp);return true;}else return false;}/*** 读取远程接口返回的内容* @return string* */ private function getContent($sGetUrl){/**/$ch = curl_init();curl_setopt ($ch, CURLOPT_URL, $sGetUrl); //设置GET的URL地址curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);//将结果保存成字符串curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);//连接超时时间s curl_setopt ($ch, CURLOPT_TIMEOUT, 10);//执行超时时间s curl_setopt ($ch, CURLOPT_DNS_CACHE_TIMEOUT, 1800);//DNS解析缓存保存时间半小时curl_setopt($ch, CURLOPT_HEADER,0);//丢掉头信息if (count($this->maGetPostData) > 0){ //存在POST数据需要提交curl_setopt($ch, CURLOPT_POST, 1); //启用POST数据curl_setopt($ch, CURLOPT_POSTFIELDS, implode('', $this->maGetPostData));//提交POST数据}$sData = curl_exec($ch);curl_close($ch);unset($ch);return $sData;}}$o = new interface_relay();unset($o);?>
