操作環境:OS:win7-64bit,brower:chrome
今天在學習jquery的ajax請求時碰到一個問題,當使用jquery中的load()函數訪問一個跨站資源(不是相同域名和端口即屬於跨站)時,如果直接訪問該資源會出現無法加載的情況。
例如有如下代碼:
1 <!-- AJAX1--> 2 <!doctype html> 3 <html> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html;charset=gb2312" /> 6 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 7 <script type="text/javascript"> 8 $(document).ready(function(){ 9 $("#btn1").click(function(){ 10 $("#p1").load("http://127.0.0.1/ajaxtest/demo.txt"); 11 }); 12 }); 13 </script> 14 </head> 15 <body> 16 <p id="p1">First Paragraph</p> 17 <button id="btn1">載入ajax</button> 18 19 </body> 20 </html>
http://127.0.0.1/ajaxtest/demo.txt內容為
<h2>jQuery and AJAX is FUN!!!</h2> <p id="p1">This is some text in a paragraph.</p>
此時打開ajax1.html會在js控制台出現如下錯誤,意思是因為缺少“Access-Control-Allow-Origin”頭,無法使用該資源。
XMLHttpRequest cannot load http://127.0.0.1/ajaxtest/demo.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
查詢了一下“Access-Control-Allow-Origin”,發現這是HTML5中定義的一個HTML頭,表示該資源允許被哪個域引用,其中*可表示所有域。更多的介紹可以看http://yuguo.us/weblog/access-control-allow-origin/ 這篇博文。
在上面的例子中,我使用本機中一個html文件去訪問127.0.0.1下的一個txt資源,因為並非同域,又沒有“Access-Control-Allow-Origin”頭,所以被服務器拒絕得到該資源。解決辦法是先訪問一個php文件,輸出“Access-Control-Allow-Origin”頭再返回該文件。
代碼修改如下:
<!-- AJAX2--> <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=gb2312" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#btn1").click(function(){ $("#p1").load("http://127.0.0.1/ajaxtest/demo.php"); //修改為demo.php }); }); </script> </head> <body> <p id="p1">Test Paragraph</p> <button id="btn1">載入ajax</button> </body> </html>
此外在服務端新建一個文件demo.php
<?php header('Access-Control-Allow-Origin:*'); $file=file_get_contents("./demo.txt"); echo $file; ?>
此時便能正常訪問了。