ajax请求
jquery ajax函数
封装了一个ajax的函数,代码如下:
var ajax = function(url, type success, error) {
$.ajax({
url: url,
type: type,
datatype: 'json',
timeout: 10000,
success: function(d) {
var data = d.data;
success && success(data);
},
error: function(e) {
error && error(e);
}
});
};
// 使用方法:
ajax('/data.json', 'get', function(data) {
console.log(data);
});
jsonp方式
有时候我们为了跨域,要使用jsonp的方法,也封装了一个函数:
function jsonp(config) {
var options = config || {}; // 需要配置url, success, time, fail四个属性
var callbackname = ('jsonp_' + math.random()).replace(".", "");
var ohead = document.getelementsbytagname('head')[0];
var oscript = document.createelement('script');
ohead.appendchild(oscript);
window[callbackname] = function(json) { //创建jsonp回调函数
ohead.removechild(oscript);
cleartimeout(oscript.timer);
window[callbackname] = null;
options.success && options.success(json); //先删除script标签,实际上执行的是success函数
};
oscript.src = options.url + '?' + callbackname; //发送请求
if (options.time) { //设置超时处理
oscript.timer = settimeout(function () {
window[callbackname] = null;
ohead.removechild(oscript);
options.fail && options.fail({ message: "超时" });
}, options.time);
}
};
// 使用方法:
jsonp({
url: '/b.com/b.json',
success: function(d){
//数据处理
},
time: 5000,
fail: function(){
//错误处理
}
});
以上就是javascript中ajax和jsonp使用技巧代码详解的详细内容。