Home >Web Front-end >JS Tutorial >Detailed explanation of code for using ajax and jsonp in javascript
Ajax request
##jquery ajax function
encapsulates an ajax function, the code is as follows: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 method
Sometimes we have to use the jsonp method in order to cross domains, which is also encapsulated A function: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(){ //错误处理 } });
The above is the detailed content of Detailed explanation of code for using ajax and jsonp in javascript. For more information, please follow other related articles on the PHP Chinese website!