jsonp牵扯到同源策略、跨域等问题,这里不细说了.
实现就是创建动态的script标签来请求后台地址:
示例:
jsonp(‘xxx.php‘, { uid: 1 }, function (res) { console.log(res) })
实例:
jsonp(‘http://localhost/server.php‘, { uid: 1 }, function (res) { console.log(res) })
1 function jsonp (url, params, callback) { 2 var funcName = ‘jsonp‘ + Date.now() + Math.random().toString().substr(2, 5) 3 4 if (typeof params === ‘object‘) { 5 var tempArr = [] 6 for (var key in params) { 7 var value = params[key] 8 tempArr.push(key + ‘=‘ + value) 9 } 10 params = tempArr.join(‘&‘) 11 } 12 13 var script = document.createElement(‘script‘) 14 script.src = url + ‘?‘ + params + ‘&callback=‘ + funcName 15 document.body.appendChild(script) 16 17 window[funcName] = function (data) { 18 callback(data) 19 delete window[funcName] 20 document.body.removeChild(script) 21 } 22 }
原文地址:https://www.cnblogs.com/cisum/p/9379193.html
时间: 2024-12-19 11:58:37