AJAX JSONP(AJAX 跨域请求)-简单小结

 

                                              AJAX 跨域请求

1、简介:  AJAX 跨域请求是 json 的一种使用模式,使自家网页获取其它网站、域名的资料,即跨域读取数据。

2、举例

例子1

描述: 获取其它网站数据

客户端页面代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AJAX跨域请求-实例</title>
</head>
<body>
    <div id="showContent"></div>
    <script>
    /*回调函数showUserName*/
    function showUserName(result, methodName){
            var html = '<ul>当前域';
            for(var i = 0; i < result.length; i++)
            {
                html += '<li>' + result[i] + '</li>';
            }
            html += '</ul>';
            $('showContent').innerHTML = html;
    }  
 </script>
<!--http://baiui.com/user/jsonp.php:别的任意网站。ajaxcallbackfunction:设置回调函数showUserName,如上script中。-->
 <script type="text/javascript" src="http://baiui.com/user/jsonp.php?ajaxcallbackfunction=showUserName"></script>
 </body>
</html>

后台服务器端jsonp.php 文件代码

<?php
header('Content-type: application/json');
//获取回调函数名
$ajaxcallbackfunction= htmlspecialchars($_REQUEST ['ajaxcallbackfunction']);
//设置json数据
$json_data = '["xiaoming","xiaozhang"]';
//输出jsonp格式的数据
echo $ajaxcallbackfunction. "(" . $json_data . ")";
?>

例子2

描述:设置文件头部Access-Control-Allow-Origin和Access-Control-Allow-Methods来实现跨域

比如有两个主机,self.code.baidu.com和www.baidu.com

现在self.code.baidu.com上要获取www.baidu.com的登陆信息,比如用户ID,用户名等。


在self.code.baidu.com的AJAX代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>self.code.baidu.com的AJAX代码</title>
</head>
<body>
    <h2>跨域资源共享(CORS)</h2>
    <div id="userInfo"></div>
    <form id="form">
        <button type="button" onclick="loadXMLDoc()">请求数据</button>
    </form>	
    <div id="myDiv"></div>
    <script> 
        function loadXMLDoc() { 
           //空对象然后添加 
           var fd = new FormData(); 
           fd.append("a", "getUserInfo"); 
           //通过表单对象创建 FormData 
           //XMLHttpRequest 原生方式发送请求,创建 XMLHttpRequest 对象
           var xhr = new XMLHttpRequest(); 
           xhr.open("POST" ,"http://www.baidu.com/has_cors.php" , true); 
           //跨域访问没有设置cors的文件,将报错 
           //xhr.open("POST" ,"http://www.baidu.com/no_cors.php" , true);  
           xhr.send(fd); 
           xhr.onload = function(e) { 
               if (this.status == 200) { 
                   eval("var data = "+this.responseText); 
                   document.getElementById("userInfo").innerHTML="Id:" + data.uid + " Name:" + data.name; 
               }; 
           }; 
        }
    </script>
</body>
</html>							

http://www.baidu.com/has_cors.php代码

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
$a = !empty($_REQUEST['a']) ? trim($_REQUEST['a']) : '';

if($a == 'getUserInfo') {
    echo json_encode(array(
        'uid' => 1,
        'name' => '测试',
    ));
} else {
    echo '';
}
?>
http://www.baidu.com/no_cors.php代码
<?php
$a = !empty($_REQUEST['a']) ? trim($_REQUEST['a']) : '';
 
if($a == 'getUserInfo') {
    echo json_encode(array(
        'uid' => 1,
        'name' => '测试',
    ));
} else {
    echo '';
}
?>
当然客户端还有更方便的写法
$(function(){
            $("#btn").click(function() {
                $.ajax({
                    url: "/info/index.jsp",
                    type: "post",
                    data: { id: '0' },
                    dataType: "json",
                    success: function(msg) {
                        console.log(msg);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest.status);
                        console.log(XMLHttpRequest.readyState);
                        console.log(textStatus);
                    },
                    complete: function(XMLHttpRequest, textStatus) {
                        this; 
                    }
                });
            });
        });

猜你喜欢

转载自blog.csdn.net/qq_31935419/article/details/81266387