JSONP解決跨域詳解

ajax的jsonp實現跨域

- 原由

由於ajax的是通過XMLHttpRequest對象請求數據的,在同源的條件(協議,域名,端口號都相同)下,這沒什麼問題,但在不同源的情況下,瀏覽器是不允許XMLHttpRequest對象跨域請求的,所以便提出很多實現跨域的方案,如iframe,jsonp等方法,但jsonp最常用,其實jquery的$.ajax跨域請求就是通過jsonp實現的

- json詳解

1.前端代碼

<script>
    function jsonp(url, arg, fn) {
        
        //1.動態創建script標籤,設置src屬性
	        //1.1 地址請求格式: url?page=1&count=10&callback=fn
        var srpt = document.createElement('script');
        var queryString = '';
        for (var key in arg) {
            queryString += key + '=' + arg[key] + '&';
        }
        var funName = 'fun_' + Math.random().toString().substr(3);
        window[funName] = fn;
        url += '?' + queryString;
        url += 'callback=' + funName;
        srpt.src = url;
     //2.將創建好的script標籤添加到頁面上
        document.body.appendChild(srpt);
    }
    //url:"",arg:{},callback
    jsonp('http://127.0.0.1:3000/home.js', {page: 1, count: 10},
            function (data) {
                console.log(data.age,1);
            }
    );
//jsonp調用,請求http://127.0.0.1:3000/home.js?age=1&count=10&callback=fun_562156256(函數名是隨機生成的,相應回來後,通過該回調函數處理取回的數據)
    jsonp('http://127.0.0.1:3000/home.js', {page: 1, count: 10},
            function (data) {
                console.log(data.age,2);
            }
    );
</script>

後端服務器代碼

const express = require('express');
const app = express();
app.get('/home.js',(req,res)=>{
    var funName  = req.query.callback;
    res.send(funName+"({name:'jack',age:21,sex:'男'})");
});
app.listen(3000);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章