Ajax跨域:jsonp还是CORS

跨域一般用jsonp,兼容性比较好。
CORS是html5最新的XHR第二版本,不支持IE8,IE9,对移动端的支持非常好。
但是考虑项目后期这部分会转到同域名下,而且网址不需要支持ie8,ie9,所以我们考虑使用html5最新的跨域资源共享(CORS)来实现跨域请求。

http://a.test.com/cross.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>sub domain</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="css/main.css">
    <script src="js/jquery-1.11.3.js"></script>
    <script src="js/jQuery.XDomainRequest.js"></script>
</head>

<body>
    <h3>跨域限制</h3>
    <button class="btn btn-primary btn-sm" onclick="crossAjax();">跨域请求</button>
    <hr />
    <h3>IE8,9跨域限制</h3>
    <button class="btn btn-primary btn-sm" onclick="ieCrossAjax();">跨域请求</button>
    <hr />
    <script>
    function crossAjax() {
        // var url = 'http://192.168.1.138:8080/msjc-admin/index';
        var url = 'http://b.test.com/test.php';

        $.ajax(url).done(function(data) {
            alert(data.name);
        }).fail(function() {
            alert('请求失败');
        });
    }

    function ieCrossAjax() {
        var url = 'http://b.test.com/test.php';

        // var xdr = new XDomainRequest();
        // xdr.open("get", url);
        // xdr.onload = function() {
        //     var data = JSON.parse(xdr.responseText)
        //     alert(data.name);
        // }
        // xdr.send();


        // GET
        // $.getJSON(url).done(function(data) {
        //     alert(data.name);
        // });

        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json'
        }).done(function(data) {
            alert(data.name);
        });

        // POST
        // POST
        // $.ajax({
        //     url: url,
        //     data: {
        //         name: 'nuanfeng',
        //         gender: 'boy'
        //     },
        //     contentType: 'text/plain',
        //     type: 'POST',
        //     dataType: 'json'
        // }).done(function(data) {
        //     console.log(data);
        // });

        // $.post(url, {
        //         name: "Donald Duck",
        //         gender: "Duckburg"
        //     },
        //     function(data, status) {
        //         alert("Data: " + data.name + "
Status: " + status);
        //     });

    }
    </script>
</body>

</html>

php - server:

<?php  
$ret = array(  
    'name' => isset($_POST['name'])? $_POST['name'] : 'myName',  
    'gender' => isset($_POST['gender'])? $_POST['gender'] : 'myGender'  
); 

// $ret = file_get_contents("php://input"); 
// $ret = $ret=>'name';
// $ret = json_encode($ret);
  
header('content-type:application:json;charset=utf8');  
// 指定可信任的域名来接收响应信息
header('Access-Control-Allow-Origin:*');  
// header('Access-Control-Allow-Methods:POST');  
// header('Access-Control-Allow-Headers:x-requested-with,content-type');  
  
echo json_encode($ret);  
?>

如果需要支持ie8,ie9,可以判断ie情况下使用XDomainRequest来实现:

var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onload = function() {
    var data = JSON.parse(xdr.responseText)
    alert(data.name);
}
xdr.send();

上面的cross.html中,我们引入了一个jQuery.XDomainRequest,它就是封装了XDR(XDomainRequest)来支持ie8和ie9. (http://www.tuicool.com/articles/Njiiamm

关于CORS更详细点的介绍:http://blog.csdn.net/fdipzone/article/details/46390573   http://www.cnblogs.com/yuzhongwusan/p/3677955.html

原文地址:https://www.cnblogs.com/woodk/p/5504864.html