Home Backend Development PHP Tutorial PHP如何实现跨域_php实例

PHP如何实现跨域_php实例

Jun 16, 2016 am 08:41 AM

因工作需要,客户端软件的一些界面用HTML+CSS+Javascript实现,这些文件放在客户端本地,以本地文件形式加载,但是有些情况下,需要连接服务器取得一些信息,如果不做任何处理,则请求失败,返回的信息如下:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

这是因为浏览器跨域策略起作用,阻止了跨域的请求。看看HTTP请求过程就知道。第一次请求后端时候,浏览器意识到是访问一个跨与资源,没有直接发送GET请求获取数据,而是发送了一个OPTIONS请求询问是否可以访问该资源。我们称之为Preflight请求,默认因为同源策略的存在,该请求返回的Header中没有'Access-Control-Allow-Origin'属性,所以访问失败。
如果要实现跨域,关键在于服务器,客户端的代码按照正常的方式编写即可。对于服务器,只需要在收到OPTIONS请求的地方,返回的头信息中增加该属性即可,代码如下:

header("Access-Control-Allow-Origin: *");
Copy after login

注意,一定要在所有信息输出到客户端之前设置。

以上所述是小编给大家介绍的PHP如何实现跨域的相关内容,希望对大家有所帮助!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

11 Best PHP URL Shortener Scripts (Free and Premium)

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Introduction to the Instagram API

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

12 Best PHP Chat Scripts on CodeCanyon

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

Notifications in Laravel

See all articles