封装的HTTP方法如下:
function $http(url,type,isAsync,time, success,error ){ var request = new XMLHttpRequest(); var timeout = false; var timer = setTimeout( function(){ timeout = true; request.abort(); }, time ); request.open(type, url,isAsync); request.onreadystatechange = function(){ if( request.readyState !== 4 ) return; if( timeout ) return; clearTimeout( timer ); if( request.status === 200 ){ success( request.responseText ); }else{ error( request.responseText ); } }; request.send(null); }
调用:
function success(data) { console.log(‘成功!‘,data); } function error(data) { console.log(‘失败!‘,data); } $http(‘abc‘,‘get‘,true,7000,success,error);
简单的封装了一下,并不像ajax一样把jsonp之类的都封装好了。
时间: 2024-10-10 05:56:05