本文介绍了在 php 中将头 Access-Control-Allow-Origin 添加到 XMLHttpResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向用 php 编写的服务器发送 XHR 请求,该请求工作正常.但在某些跨域来源不允许加载和处理来自服务器的响应.它抛出错误

I am sending XHR request to server written in php which is working fine.but at some cross domain origin are not allowing loading and processing the response from server. it is throwing error

XMLHttpRequest cannot load http://mydomain/getInfo?blabla. Origin http://www.somedomain.com is not allowed by Access-Control-Allow-Origin.

那么如何在 php 的响应头中设置 Access-Control-Allow-Origin?

so how can I set Access-Control-Allow-Origin in the response headers in php?

推荐答案

如果您的 JavaScript 在 example.com 上运行,并且您请求的服务器在 example.net 中.确保它允许您的 js 通过此标头运行的页面

If your JavaScript runs on example.com and the server you are requesting to is in example.net. Make sure it allows the page your js is running by this header

Access-Control-Allow-Origin: http://example.com/ajax.html

还需要将 Origin 标头从 ajax 发送到服务器

Also you need to send Origin header from ajax to the server

Origin: http://example.com/ajax.html

更多信息可以在 HTTP 访问控制 (CORS) 上找到

More information can be found on HTTP access control (CORS)

这篇关于在 php 中将头 Access-Control-Allow-Origin 添加到 XMLHttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:52