jquery学习笔记1-Ajax跨站请求资源

    操作环境: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 >First Paragraph</p>
17     <button >载入ajax</button>
18 
19 </body>
20 </html>
http://127.0.0.1/ajaxtest/demo.txt内容为
<h2>jQuery and AJAX is FUN!!!</h2>
<p >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 >Test Paragraph</p>
	<button >载入ajax</button>

</body>
</html>

  

此外在服务端新建一个文件demo.php

<?php
	header('Access-Control-Allow-Origin:*');
	$file=file_get_contents("./demo.txt");
	echo $file;
	?>

此时便能正常访问了。