jsop之---实现过程

JSONP(JSONP - JSON with Padding是JSON的一种“使用模式”),利用script标签的src属性(浏览器允许script标签跨域)

跨域访问,非同源访问

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <p>
        <input type="button" onclick="Jsonp1();"  value='提交'/>
    </p>

    <p>
        <input type="button" onclick="Jsonp2();" value='提交'/>
    </p>
  底层真实的实现过程
    <script type="text/javascript" src="jquery-1.12.4.js"></script>
    <script>
        function Jsonp1(){
            var tag = document.createElement('script');
            tag.src = "http://c2.com:8000/test/";
            document.head.appendChild(tag);
            document.head.removeChild(tag);

        }
  封装后的使用方法
        function Jsonp2(){
            $.ajax({
                url: "http://c2.com:8000/test/",
                type: 'GET',
                dataType: 'JSONP',
                success: function(data, statusText, xmlHttpRequest){
                    console.log(data);

       jsonp: 'callback',     

      固定用法,加上以下两个参数,url相当于http://127.0.0.1:9000/xiaokai.html?callback=func
                 jsonpCallback: 'func'  指定对方需要返回的函数名是func
            })
        }
        function func(arg) {
            console.log(arg);
        }
    </script>
</body>
</html>

基于JSONP实现跨域Ajax - Demo

猜你喜欢

转载自www.cnblogs.com/jinxf/p/9164360.html