js 實現JSONP

編寫一個 jsonp.html 內容以下:html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<!--
    點擊 button 後添加一個 script
    <script>
        list([11,22,33,44])
    </script>
-->
</head>
<body>
    <input type="button" onclick="jsonpRequest();" value="跨域請求" />

    <script>
        TAG = null;
        function jsonpRequest() {
            TAG = document.createElement('script');
            TAG.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403';   // 對方網站協商返回 list([11,22,33,44]) 數據
            document.head.appendChild(TAG);          // 在 head 處添加<script>標籤
        }

        // 定義 list() 函數
        function list(arg) {
            console.log(arg);                       // 打印 list() 函數內的參數
            document.head.removeChild(TAG);         // 在 head 處移除<script>標籤
        }
    </script>

</body>
</html>

相關文章
相關標籤/搜索