本文先介紹如何為apache配置多網域名稱,然後再用JSONP(JSON with Padding)來解決JSON的跨域問題。
閱讀本文之前,推薦先參閱《JSON進階第二篇AJAX方式傳遞JSON資料》。
一.apache配置多網域名稱
在apache的conf目錄下找到httpd.conf,然後在該檔案最後增加如下內容:
# 聲明使用虛擬機器主機過濾規則
NameVirtualHost*:80
#虛擬機器主機localhost
<VirtualHost*:80>
ServerName localhost
DocumentRoot"D:\xampp\htdocs\www"
</VirtualHost>
#虛擬機器主機test.mw.com
<VirtualHost*:80>
ServerName test.mw.com
DocumentRoot"D:\xampp\htdocs\test.mw.com"
</VirtualHost>
其中第一個是保證原有的localhost還可以繼續工作,第二個為新加網域名稱test.mw.com。
然後再修改host檔案(在C:\Windows\System32\drivers\etc\)
增加:
# test.mw.com
127.0.0.1test.mw.com
注意修改httpd.conf後要重啟下apache服務。
將《JSON進階第二篇 AJAX方式傳遞JSON資料》文中的json2.php拷貝到D:\xampp\htdocs\test.mw.com目錄中再在瀏覽器中輸入網址http://test.mw.com/json2.php
運行結果如下:
在瀏覽器中能看到如上所示的JSON字串說明已經成功為apache增加了新的網域名稱,接下來就來體驗下JSON的跨網域名稱問題。
將json2.html中“$.post("json2.php", {}, function(data){”的“json2.php”改成“http://test.mw.com/json2.php”表示我們要引用test.mw.com網域名稱下的json2.php檔案。然後在json2.html中點擊按鈕,可以發現沒任何效果。
用Firefox的Firebug查看點擊按鈕後AJAX響應的詳細過程,可以看到AJAX請求資訊已經發送到伺服器上了(就是那個127.0.0.1:80),但因為安全性問題,伺服器返回的資料被屏蔽了——這就是大名鼎鼎的跨域問題。
二.JSONP——解決JSON跨域問題
使用JSONP(JSON with Padding)就可以解決JSON的跨域問題,JSONP的原理可以訪問http://zh.wikipedia.org/zh-cn/JSONP,簡單的說就是利用了<script>標籤擁有的開放策略(相對於同域策略)。下面介紹如何使用JSONP。
JSONP的使用分為二步:
第一將html檔案中的
$.post("http://test.mw.com/json2.php",{}, function(data){
改成
$.getJSON("http://test.mw.com/json2.php?format=json&jsoncallback=?",{}, function(data){
第二將json2.php最後的
echo$article_json;
改成
echo$_REQUEST['jsoncallback'] . "(" . $article_json . ")";
修改這二個地方後就可以解決JSON的跨域問題了。
下面也給出完整的樣本程式,分為json2.php和json2.html, json2.html上有個按鈕,按下後將發送AJAX請求得到json2.php返回的跨域JSON資料。注意和上一篇《JSON進階第二篇 AJAX方式傳遞JSON資料》文中的代碼進行比較。
1.Json2.php
<?php// by MoreWindows( http://blog.csdn.net/MoreWindows )$article_array = array(array("id"=>"001","title"=>"PHP訪問MySql資料庫 初級篇", "link"=>"http://blog.csdn.net/morewindows/article/details/7102362"),array("id"=>"001","title"=>"PHP訪問MySql資料庫 中級篇 Smarty技術", "link"=>"http://blog.csdn.net/morewindows/article/details/7094642"),array("id"=>"001","title"=>"PHP訪問MySql資料庫 進階篇 AJAX技術", "link"=>"http://blog.csdn.net/morewindows/article/details/7086524"),);$article_json = json_encode($article_array);//echo $article_json;echo $_REQUEST['jsoncallback'] . "(" . $article_json . ")";?>
2.Json2.html // by MoreWindows( http://blog.csdn.net/MoreWindows )
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>ajax方式請求跨域的json資料</title><script type="text/javascript" src="../jquery-1.7.min.js"></script><script type="text/javascript">//顯示提示function OnMouseEnterDivInfo(thisObj, title){ $("#article_link").css("position","absolute"); $("#article_link").css("left","20px"); $("#article_link").css("top",$(thisObj).offset().top + $(thisObj).height()); $("#article_link").html("連結地址" + title); $("#article_link").slideDown("fast"); $(thisObj).css("background-color","red");}//隱藏提示function OnMouseLeaveDivInfo(thisObj){ $("#article_link").hide(); $(thisObj).css("background-color","yellow");} //jquery通過AJAX方式得到JSON資料$(document).ready(function(){ $("#GetDataBtn").click(function(){ //$.post("http://test.mw.com/json2.php", {}, function(data){ $.getJSON("http://test.mw.com/json2.php?format=json&jsoncallback=?", {}, function(data){ var g_jsonstr = eval(data); var ilen = g_jsonstr.length; var detailhtml = ""; for (var i = 0; i < ilen; i++) { var divhtml = '<div id=\"div_' + i + '\" onmouseenter=\"OnMouseEnterDivInfo(this, \' '+ g_jsonstr[i]['link'] + '\');\" onmouseleave=\"OnMouseLeaveDivInfo(this);\" >'; divhtml += '<h1>' + g_jsonstr[i]['title'] + '</h1>'; divhtml += '</div>'; detailhtml += divhtml; } $("#detail").html(detailhtml);//產生新的標題區 $("#detail").slideDown("slow"); }); });});</script><style type="text/css">div{font-family:sans-serif;}</style></head><body><input type="button" id="GetDataBtn" value="產生資料" /><div id="detail"></div><p><span id="article_link" style="display:none;z-index:100"></span></p></body></html>
再用Firefox的Firebug查看點擊按鈕後AJAX響應的詳細過程,可以發現已經可以收到跨域後的JSON資料了。
有興趣的筒子可以再試試這種方式:
將http://test.mw.com/json2.php的
echo$_REQUEST['jsoncallback'] . "(" . $article_json . ")";
換成
echo"ShowData($article_json)";
再將json2.html的
$(document).ready(function(){... }
換成
function ShowData(data){ var g_jsonstr = eval(data); var ilen = g_jsonstr.length; var detailhtml = ""; for (var i = 0; i < ilen; i++) { var divhtml = '<div id=\"div_' + i + '\" onmouseenter=\"OnMouseEnterDivInfo(this, \' '+ g_jsonstr[i]['link'] + '\');\" onmouseleave=\"OnMouseLeaveDivInfo(this);\" >'; divhtml += '<h1>' + g_jsonstr[i]['title'] + '</h1>'; divhtml += '</div>'; detailhtml += divhtml; } $("#detail").html(detailhtml);//產生新的標題區 $("#detail").slideDown("slow");}//jquery通過AJAX方式得到JSON資料$(document).ready(function(){ $("#GetDataBtn").click(function(){ //jsonp原理--利用<script>標籤的開放策略 var script = document.createElement('script'); script.setAttribute('src', "http://test.mw.com/json2.php"); document.getElementsByTagName('head')[0].appendChild(script);}
來試試,同樣可以得到資料的(有一點不足——此時滑鼠移動到標題是不會觸發提示的)。
另外,關於JSON有個小小的問題要注意下:
$array1 = array("a", "b");$array2 = array('001'=>"a", '002'=>"b");$json1 = json_encode($array1);$json2 = json_encode($array2);echo $json1 . "<br />";echo $json2 . "<br />";
會輸出
["a","b"]
{"001":"a","002":"b"}
這說明,$json1是數組,而且$json2是對象。將$json1和$json2傳到js代碼中,$json1.length是合法的,但$json2.length是未定義的。讀者可以對比本篇json2.php中數組$article_array與上一篇的區別。
至此,JSON進階三篇全部完成。下面列出目錄,以供參考:
1.《JSON進階第一篇 在PHP與javascript 中使用JSON》
2.《JSON進階第二篇 AJAX方式傳遞JSON資料》
3.《JSON進階第三篇 apache多網域名稱及JSON的跨域問題(JSONP)》
轉載請標明出處,原文地址:http://blog.csdn.net/morewindows/article/details/7235992