上代碼:
(function (window, document, undefined) {
// 1、掛載回調函數
// 2、將data轉換爲字符串形式
// 3、處理url中的回調參數
// 4、創建一個script標籤
// 5、將script標籤放到頁面中
var callbackFnName = 'my-jsonp' + Math.random();
window[callbackFnName] = callback;
var jsonp = function (url, data, callback) {
var queryString = url.indexOf('?') === -1 ? '?' : '&';
for (var key in data) {
queryString += key + '=' + data[key] + '&';
}
queryString += 'callback = '+ callbackFnName;
var scriptEle = document.createElement('script');
scriptEle.src = url + queryString
document.body.appendChild(scriptEle);
window.$jsonp = jsonp
}
})(window, document)
使用組件代碼:
(function(){
$jsonp('要跨域請求的地址', {'要傳入的參數'}, function (data) {
//拿到後臺數據後的回調函數
})
})