1.No ‘Access-Control-Allow-Origin’ header is present on the requested
最近在接html5的渠道,遇到了跨域的问题,使用 js 的 ajax post 或者get 方法,只要目标URL稍微有点不同,就会有跨域问题,浏览器会因为安全问题自动拦截。
这个问题其实不是客户端能解决的,最好是目标URL的服务器代码是你可以控制的,最方便的解决方案是在你访问的服务器端页面加代码。比如你现在的地址是 http://a.company.com 要访问 http://b.company.com ,你应该在 http://b.company.com 中加入允许跨域访问的代码。
PHP代码如下:
header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Max-Age: 1000'); header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
2.跳转还是会有问题
比如你又在http://b.company.com 的服务器代码又跳转到 http://c.other.com , 而且 http://c.other.com 不受你控制,那么你可以使用这样的小技巧,返回url给js,让js通过 location.href = “http://c.other.com” 来跳转。
1737