- jsonp解决web端JavaScript跨域请求
利用 < script > 的 src 属性对服务器请求拉取数据字符串,然后通过回调函数获取接口数据
/**
* 封装CORS (跨域请求)jsonp方法
* @param url 访问地址信息
* @param params 请求参数格式:"key1=data1&key2=data2"
* @param callback 回调函数
*/
function jsonp(url, callback, params = null) {
var script = document.createElement('script')
var functionName = 'callfunction' + Date.now() + Math.random().toString().substr(2, 5);
var data = params != null ? '&' + params : '';
script.src = url + '&callback=' + functionName + data
document.body.appendChild(script)
window[functionName] = function (res) {
delete window[functionName]
typeof callback === "function" && callback(res)
}
document.body.removeChild(script)
}
//调用示例
var data = 'key1=data1&key2=data2'
jsonp('jsonpurl', function (res) {
console.log(res)
}, data)
- 原生JS封装ajax请求
/**
* ajax封装
* @param method 传输方式GET , POST
* @param url 传输地址
* @param data 参数
* @param callback 回调函数
*/
function ajax(method, url, callback, data = null) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
xhr.open(method, url)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(data)
xhr.onreadystatechange = function () {
if (this.readyState != 4) {
return
}
typeof callback == 'function' && callback(this.response)
}
}
//调用示例
ajax('GET', 'url', function (res) {
console.log(res)
})