zoukankan      html  css  js  c++  java
  • PHP Ajax 跨域问题最佳解决方案

    本文通过设置Access-Control-Allow-Origin来实现跨域。

    例如:客户端的域名是client.runoob.com,而请求的域名是server.runoob.com。

    如果直接使用ajax访问,会有以下错误:

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

    1、允许单个域名访问

    指定某域名(http://client.runoob.com)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加如下代码:

    header('Access-Control-Allow-Origin:http://client.runoob.com');

    2、允许多个域名访问

    指定多个域名(http://client1.runoob.com、http://client2.runoob.com等)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加如下代码:
    $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';  
      
    $allow_origin = array(  
        'http://client1.runoob.com',  
        'http://client2.runoob.com'  
    );  
      
    if(in_array($origin, $allow_origin)){  
        header('Access-Control-Allow-Origin:'.$origin);       
    }

    3、允许所有域名访问

    允许所有域名访问则只需在http://server.runoob.com/server.php文件头部添加如下代码:

    header('Access-Control-Allow-Origin:*');

    4、已测试

    header("Content-type:application/json");
    header("Access-Control-Allow-Origin:*");
    header("Access-Control-Allow-Methods:GET,OPTIONS,POST");
    header("Access-Control-Allow-Credentials:true");
    header("Access-Control-Allow-Headers:Content-Type,Content-Length,Accept-Encoding,X-Requested-With,Origin");



  • 相关阅读:
    自己常用的数据库操作语句
    我被SQL注入撞了一下腰
    分页
    reset.css
    创建对象的多种方式
    js 数组去重
    学习JS防抖【节流】
    localStorage.js
    vue 项目移动端使用淘宝自适应插件 环境配置
    Vue项目搭建
  • 原文地址:https://www.cnblogs.com/finnlee/p/7751791.html
Copyright © 2011-2022 走看看