返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
PHP

PHP-Ajax Cross-Domain Problem Best Solution

Preface Ajax cross-domain problems are very common in development. For example, the domain of the webpage is client.abc.com, while the domain of the request is server.abc.com. If you access it directly with ajax, you will get the following error: XMLHttpRequest cannot load http://server.abc.com/server.php. No 'Access-Control-Allow-Origin' header is present

曦远 (DealiAxy)约 5 分钟
目录7 个章节

Preface

Ajax cross-domain problems are very common in development. For example, the domain of the webpage is client.abc.com, while the domain of the request is server.abc.com. If you access it directly with ajax, you will get the following error:

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

The Simplest Solution

header('content-type:application/json;charset=utf8');  
// 指定允许其他域名访问  
header('Access-Control-Allow-Origin:*');  
// 响应类型  
header('Access-Control-Allow-Methods:POST');  
// 响应头设置  
header('Access-Control-Allow-Headers:x-requested-with,content-type');

1. Allow Access from a Single Domain

To allow a specific domain client.abc.com to make cross-domain requests, you only need to add the following code at the top of the server.abc.com/a.php file:

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

2. Allow Access from Multiple Domains

To allow multiple domains, add the following code at the top of the server.php file:

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
//$_SERVER['HTTP_ORIGN']获得请求访问的域名

$allow_origin = array(
  'http://client.abc.com',
  'http://client2.abc.com'
);

if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}

3. Allow Access from All Domains

To allow all domains to access, you only need to add the following code at the top of the php file:

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

About

To learn more interesting tricks, please follow my WeChat official account: DealiAxy Every article is collected on my blog: blog.deali.cn

_EOF_

PHP-Ajax Cross-Domain Problem Best Solution

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

PHP7-0-+-Swoole-环境配置

前言 Swoole是一个面向生产环境的 PHP 异步网络通信引擎。 使 PHP 开发人员可以编写高性能的异步并发 TCP、UDP、Unix Socket、HTTP,WebSocket 服务。Swoole 可以广泛应用于互联网、移动通信、企业软件、云计算、网络游戏、物联网(IOT)、车联网、智能家居等领域。 使用 PHP + Swoole 作为网络通信框架,可以使企业 IT 研发团队的效率大大提升,

2021-12-18 · PHP · 约 1 分钟

C#学习(二)匿名方法和委托的多种使用方式

前言 上次简单介绍了委托的概念和使用,今天继续,并且引入匿名方法的概念,匿名方法在很多语言里面都有,比如Python、js、java8,尤其js,前端小伙伴可能深受js回调地狱之苦,这里面匿名方法功不可没。 js的匿名方法就像这样: 这还没用lambda,因为我想下篇再介绍lambda。 document.querySelector('.btn').onclick = function () {

2021-12-18 · C# · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…