zoukankan      html  css  js  c++  java
  • 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 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;
    	?>
    

    此时便能正常访问了。

  • 相关阅读:
    springboot使用war包部署到外部tomcat
    html只允许输入的数据校验,只允许输入字母汉字数字等
    转:执行ajax加载页面中的js
    php 解析xml 的四种方法(转)
    Php 获取xml中的节点值
    php中DOMDocument简单用法(XML创建、添加、删除、修改)
    PHP对XML文件操作详细
    转载 PHP 程序员学数据结构与算法之《栈》
    php读取二进制流(C语言结构体struct数据文件)的深入解析
    关于php和C语言接口的结构传递问题,udp,tcp通信
  • 原文地址:https://www.cnblogs.com/stariit/p/3532996.html
Copyright © 2011-2022 走看看