二、如何实现AJAX跨域

为何有跨域问题:

ajax之所以需要“跨域”,罪魁祸首就是浏览器的同源策略。即,一个页面的ajax只能获取这个页面相同源或者相同域的数据。

如何叫“同源”或者“同域”呢?——协议、域名、端口号都必须相同。例如:

http://google.com 和 https://google.com 不同,因为协议不同;

http://localhost:8080 和 http://localhost:1000 不同,因为端口不同;

http://localhost:8080 和 https://google.com 不同,协议、域名、端口号都不同,根本不是一家的。

根据同源策略,我自己做的一个网页 http://localhost:8080/test.html 就无法通过ajax直接获取 http://google.com 的数据。

解决方法一:JSONP :注意:json只能发get请求,无法发AJAXpost请求,有参数传递的话,加载请求连接后面

doem:如从www.34.com请求www.33.com,

a、本地服务器这样写

b、对方服务器这样写

解决方法二:请出和前端绝配的php

doem2:

<script type="text/javascript">
        function showweather(){
            //利用ajax调用天气信息
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.readyState==4){
                    eval("var info="+xhr.responseText);
                    var s = "";
                    s += "地址:"+info.weatherinfo.city+"<br />";
                    s += "温度:"+info.weatherinfo.temp+"<br />";
                    s += "风向:"+info.weatherinfo.WD+"<br />";

                    document.getElementById('result').innerHTML = s;
                }
            }
            xhr.open('get','./data.php');
            xhr.send(null);
          /*比GET请求多了一步
 	   xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 	   另外,数据是通过send方法发送的
 	   xhr.send("qs=true&userName=abc&pwd=123456");
*/

} window.onload = function(){ showweather(); } </script>
<?php

//跨域请求天气信息

$url = "http://www.weather.com.cn/adat/sk/101010100.html";
//file_get_contents(file/url地址);
//url地址:请求该地址,并返回信息

$cont = file_get_contents($url);
echo $cont;
原文地址:https://www.cnblogs.com/yexiangwang/p/5061030.html