Ajax-PHP支持IE和Firefox跨域访问的解决方案  2008-04-17   Web  

如果说的cross-browser(兼容浏览器)问题尚可解决,那么的致命弱点cross-domain(跨域)却是本身无能为力了!可以采用PHP的CURL类库来实现代理,但是,许多虚拟主机并不提供CRUL类库,怎么办?本文提出了不使用CRUL(使用SOCKET)实现PHP程序的跨域代理,支持IE和Firefox以及其他浏览器。
实现的跨域访问功能,需要服务器端进行支持,以下两种方法比较实用:
1、服务器程序代理
使用PHP的CURL类库来实现代理的代码:
// Hardcode the hostname
define(’HOSTNAME’, ‘http://api.local.yahoo.com/’);
// Get the REST call path from the application
$path = $_GET['path'];

// The URL to fetch is the hostname + path
$url = HOSTNAME.$path;
// Open the Curl session
$session = curl_init($url);
// Don’t return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Make the call
$xml = curl_exec($session);

// The web service returns XML
header(”Content-Type: text/xml”);

echo $xml;
curl_close($session);

2、服务器软件代理
利用APACHE的重写机制:
RewriteEngine on
RewriteRule ^/call/(.*)$ http://api.local.yahoo.com/$1 [P]

如果网站在虚拟主机上,WEB服务器既没有安装CURL,也不能对Apache进行重写设置,怎么办?
下面重点说说如何使用SOCKET函数fsockopen、fwrite和fgets实现跨域方案的PHP程序代理:
PHP程序:myajax.php
<?php

$url_p = parse_url($_GET['u']);
$host = $url_p["host"];

if(!preg_match(”/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/”,$host)){
// 解析域名
$ip=gethostbyname($host);
if(!preg_match(”/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/”,$ip)){
//如果不是域名,则返回。
return -1;
}
}
$port = intval($url_p["port"]);
if(!$port) $port=80;
$path = $url_p["path"];
if(!$path){
$path=”/”;
}
$fp = fsockopen($host, $port, $errno, $errstr, 20);
if(!$fp) {
return false;
} else {
$out = “GET ” . $path . ” HTTP/1.1\r\n”;
$out .= “Host:” . $host . “\r\n”;
$out .= “Connection: Close\r\n\r\n”;
fwrite($fp, $out);
$html = “”;
while (!feof($fp)) {
$html .= fgets ( $fp, 128 );
}
}
fclose ($fp);
//显示返回的信息,如果是HTTP请求,包括头部和内容两个部分
echo $html;
?>

客户端:
<script language=”javascript”><!–
function ajaxCrossDomain(){
document.getElementById(”http_response”).innerHTML=”";
var xmlHttp=false;
try{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”);
}catch(e){
try{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}catch(e){
xmlHttp=false;
}
}
if(!xmlHttp && typeof XMLHttpRequest!=”undefined “){
xmlHttp=new XMLHttpRequest();
}
xmlHttp.open(”GET”,”/myajax.php?u=http://www.no1focus.com”,false);
xmlHttp.send(null);
if (xmlHttp.status == 200) {
document.getElementById(”http_response”).innerHTML=xmlHttp.responseText;
}
}
//–>
<input value=”确认” onclick=”javascript:ajaxCrossDomain();” type=”button”>
<div id=”http_response”></div>

标签:


 发表评论

(必填)

(必填)

评论(必填,最多字数:100):