做js的ajax應(yīng)用時楞遏,會遇到你需要請求的接口并不在你當(dāng)前域下茬暇,此時就會出現(xiàn)跨域訪問的問題,瀏覽器會禁止你請求這個接口寡喝。
此時怎么訪問這個WebService的接口呢?
一個簡單的辦法就是在本域的服務(wù)器上预鬓,增加一個轉(zhuǎn)發(fā)層巧骚,將瀏覽器上過來的請求接收后赊颠,通過服務(wù)器將這個請求轉(zhuǎn)發(fā)到對應(yīng)的WebService上,然后把返回結(jié)果再取回后劈彪,送回js的請求頁面。
一般而言這個是解決跨域訪問最安全與最具兼容性的辦法沧奴。
下面是我寫的一個php腳本痘括,可以完成這個轉(zhuǎn)發(fā)過程,僅供參考:
[php] view plain copy
<?php
/**
* ajax業(yè)務(wù)處理中的接口轉(zhuǎn)發(fā)層滔吠,解決ajax跨域訪問的問題
* 工作原理:問請求通過本程序做中轉(zhuǎn),在本地服務(wù)器層完成與遠(yuǎn)程服務(wù)接口的交互
* 備注:使用時 URL_ROOT 這個參數(shù)需要根據(jù)你的目標(biāo)接口地址進(jìn)行修改疮绷,本轉(zhuǎn)發(fā)層之能用于單接口的Web Service接口服務(wù)
* 程序支持POST數(shù)據(jù)與GET數(shù)量的同時轉(zhuǎn)發(fā);
* @version 1.0.0.2
* */
class interface_relay
{
/**接口根地址(此處是需要修改的地方)*/
const URL_ROOT = 'http://api.air-id.net/InterFace/';
/**字符集*/
const CHARSET = 'UTF-8';
/**GET*/
private $msGets = '';
/**POST*/
private $maGetPostData = array();
function __construct()
{
$this->getPOST();
$this->getGET();
if($this->msGets != '' || count($this->maGetPostData) > 0)
{ //存在輸入數(shù)據(jù)
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數(shù)據(jù)
* @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數(shù)據(jù)
* @return bool
* */
private function getGET()
{
/*取得GET內(nèi)容*/
if (count($_GET) > 0)
{
$aTmp = array();
foreach ($_GET as $sKey => $sVal)
$aTmp[] = $sKey .'='. urlencode($sVal);
$this->msGets = implode('&', $aTmp);
return true;
}
else
return false;
}
/**
* 讀取遠(yuǎn)程接口返回的內(nèi)容
* @return string
* */
private function getContent($sGetUrl)
{
/**/
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $sGetUrl); //設(shè)置GET的URL地址
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);//將結(jié)果保存成字符串
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);//連接超時時間s
curl_setopt ($ch, CURLOPT_TIMEOUT, 10);//執(zhí)行超時時間s
curl_setopt ($ch, CURLOPT_DNS_CACHE_TIMEOUT, 1800);//DNS解析緩存保存時間半小時
curl_setopt($ch, CURLOPT_HEADER,0);//丟掉頭信息
if (count($this->maGetPostData) > 0)
{ //存在POST數(shù)據(jù)需要提交
curl_setopt($ch, CURLOPT_POST, 1); //啟用POST數(shù)據(jù)
curl_setopt($ch, CURLOPT_POSTFIELDS, implode('', $this->maGetPostData));//提交POST數(shù)據(jù)
}
$sData = curl_exec($ch);
curl_close($ch);
unset($ch);
return $sData;
}
}
$o = new interface_relay();
unset($o);
?>