Firefox/Chrome/IE Ajax 怎样设置允许跨域请求

一般js出现跨域请求时时,浏览器错误为

chrome错误:

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

Firefox错误:

已阻止跨域源请求:同源策略禁止取位于 http://...xxx 的远程资源.(原因: CORS 头缺少 'Access-Control-Allow-Origin')

IE错误:

SEC7118: http://127.0.0.1/data/login.php 的 XMLHttpRequest 需要跨域资源共享(CORS)。

SEC7120: 在 Access-Control-Allow-Origin 标头中未找到源 http://localhost:8080。

SCRIPT7002: XMLHttpRequest: 网络错误 0x80070005, 拒绝访问。


其实这个错误提示已经很明显了,只要在请求的服务器端的页面加个 CORS 头就好了,但这个设置还是有点技巧的,请看如下php页面代码

<?php
header("Access-Control-Allow-Origin: http://localhost:8080");
sleep(3);
header("Content-type:text/html;charset=utf-8");
$username = $_POST['name'];
$pass = $_POST['pass'];

$arr["success"] =1;

echo json_encode($arr);?>

关键:

header("Access-Control-Allow-Origin: http://localhost:8080");

加这个header就可以让你的请求顺利跨域了,注意参数值必须是准确的域名,不能直接

header("Access-Control-Allow-Origin: *"); //这样是不行的,因为标准规范说不允许广泛匹配

我在localhost:8000的webpack-dev-server,请求本地的php server localhost:80/data/login.php

var url = "http://127.0.0.1/data/login.php";
      var cont={};
      cont.name = name;
      cont.pass = pass;
      var result=0;//ajax请求是否正确
      $.ajax({
        url:url,
        type:'post',
        dataType:'json',
        data:cont,
        success:function(data){
          result = data.success;
          console.log("error result=",result);
          window.location.href="/#/info";
        },
        error:function(data){
          result = data.success;
          console.log("error result=",result);
        }
       });
      console.log("ajax quest done!")

测试这样设置Firefox/Chrome/IE都可以正常访问!!!

至于网上说的Firefox设置about:config,还有在ajax open 方法前运行一行代码那都是扯淡,完全不能用(也可能是高级版本浏览器已经禁用这样的方法吧, 不知道是否如此)!!!

大家有需要可能试一下这样的写法!!!!

猜你喜欢

转载自blog.csdn.net/cen_cs/article/details/77285252