ajax本地跨域请求以及解决方法

什么是跨域?

我们通常所说的跨域是狭义的,是由浏览器同源策略限制的一类请求场景。所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个ip地址,也非同源,只要没有同时满足这三个条件的请求即为跨域请求,跨域请求控制台一般会出现类似错误:

XMLHttpRequest cannot load http://xxxxx.php.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://xxx' is therefore not allowed access.  

设置本地跨域

首先我们在本地设置本地跨域请求,首先需要安装wamp服务器,其默认的localhost端口为80,我们找到wamp的安装路径,如我的是安装在D盘,则在D:\wamp\bin\apache \apache2.4.9\conf\中打开httpd.conf文件,在Listen [::0]:80语句下添加Listen [::0]:8011,点击保存,重启wamp或Apach,这样我们就配置了一个localhost:8011端口。接下来在wamp\www文件夹中新建test1和test2文件夹,在test1下新建index文件,在test2文件夹下新建index2.php文件。

方法一:

1)test1/index.html文件js代码如下:

<script>
   $(function(){
        $.ajax( {
            url: "http://localhost:8011/test2/index2.php",
            type: 'get',
           dataType: 'jsonp', // 请求方式为jsonp
           jsonpCallback: "onBack", // 自定义回调函数名
           success: function(data){
              console.info(data)
           }
       });
 });
</script>

2)test2/index2.php文件代码如下:

<?php
     $callback=$_GET['callback'];
     $data=array('a'=>1,'b'=>2,'c'=>3);
     echo $callback.'('.json_encode($data).')';
?>

这样就可以进行ajax访问了。

方法二:

1)test1/index.html文件js代码如下:

<script>
  function dosomething(jsondata){
        console.log(jsondata)
  }
</script>
<script src="http://localhost:8011/test2/index2.php?callback=dosomething"></script>

2)test2/index2.php文件代码同方法一的test2/index2.php

这样第二种方法也ok

方法三:

1)test1/index.html文件js代码如下:

$.ajax({
     url: 'http://localhost:8011/test2/index2.php?callback=myFunction',
     type: 'get',
     data: {},
     success: function(json){
     console.log(json)
     },
     error: function(){
     alert('fail');
     }
 });

2)test2/index2.php文件代码:

<?php
     header('Access-Control-Allow-Origin:*');
     $callback=$_GET['callback'];
     $data=array('a'=>1,'b'=>2,'c'=>3);
     echo $callback.'('.json_encode($data).')';
?>

这样第三种方法也行啦

请求方式:

1)在html的ajax请求中dataType: 'jsonp',这句是关键,没有这句就没法进行ajax请求。这也就是jsonp的跨域请求方式。缺点就是只能通过GET的请求方法,不能用POST。

2)第二种方法是利用script的src不受同源限制,进行的方法回调进行跨域请求。

3)第三种方法是跨域资源共享(CORS),通过在请求文件添加header('Access-Control-Allow-Origin:*');[//指定允许其他域名访问]实现跨域的,可以多种请求方法。

4)还有其他的方法,这边就不一 一讲述啦,如有需要大家可以参考其他优秀文章

结语:

新人学习ajax跨域的小测试,如有不足之处,欢迎指正哈!

github下载地址:https://github.com/sharebetter/ajax

posted @ 2018-03-11 13:36  HM4041812  阅读(500)  评论(0编辑  收藏  举报