跨域說明
所謂同源是指,域名,協議,端口均相同,不明白沒關係,舉個例子:
http://www.123.com/index.html 調用 http://www.123.com/server.php (非跨域)
http://www.123.com/index.html 調用 http://www.456.com/server.php (主域名不同:123/456,跨域)
http://abc.123.com/index.html 調用 http://def.123.com/server.php (子域名不同:abc/def,跨域)
http://www.123.com:8080/index.html 調用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)
http://www.123.com/index.html 調用 https://www.123.com/server.php 協議不同:http/https,跨域
請注意:localhost和127.0.0.1雖然都指向本機,但也屬於跨域。
解決方法
(1).代理
例如www.123.com/index.html需要調用www.456.com/server.php,可以寫一個接口
www.123.com/server.php,由這個接口在後端去調用www.456.com/server.php並拿到返回值,
然後再返回給index.html,這就是一個代理的模式。相當於繞過了瀏覽器端,自然就不存在跨域問題。
(2).php接口的腳本中加入
header('Access-Control-Allow-Origin:*');//允許所有來源訪問
header('Access-Control-Allow-Method:POST,GET');//允許訪問的方式