天天看点

js跨域请求问题

通过动态插入<script>到页面,src的地址里包含返回执行函数callback参数,请求的页面操作函数并带有数据callback(data)

<html>

<head>

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

    <title>js跨域请求问题</title>

    <meta content="IE=7" http-equiv="x-ua-compatible" />

</head>

<body>

    <!-- main -->

    <div id="main">

        <input type="button" οnclick="get()" class="apibtn" value="查看结果" />

    </div>

    <div id="result" style="word-break: break-all;">

    </div>

    <script type="text/javascript">

        var fn = {};

        function load_script(xyUrl, callback) {

            var head = document.getElementsByTagName('head')[0];

            var script = document.createElement('script');

            script.type = 'text/javascript';

            script.src = xyUrl;

            //借鉴了jQuery的script跨域方法

            script.onload = script.onreadystatechange = function () {

                if ((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {

                    callback && callback();

                    // Handle memory leak in IE

                    script.onload = script.onreadystatechange = null;

                    if (head && script.parentNode) {

                        head.removeChild(script);

                    }

                }

            };

            // Use insertBefore instead of appendChild  to circumvent an IE6 bug.

            head.insertBefore(script, head.firstChild);

        }

        function get() {

            //debugger;

            var callbackName = 'cbk_' + Math.round(Math.random() * 10000);    //随机函数名

            var xyUrl = "http://localhost/api/get_cate_nums.php?cityid=2419&callback=fn." + callbackName;

            //动态创建script标签

            load_script(xyUrl);

            fn[callbackName] = function (xyResult) {

                //debugger;

                delete fn[callbackName];    //调用完需要删除改函数

                callback && callback(xyResult);

            }

        }

        function callback(xyResult) {

            document.getElementById("result").innerHTML = "返回结果:" + xyResult;

        }

    </script>

</body>

</html>

对网上的代码做了些修改