首页 > 代码库 > 原生js实现ajax方法
原生js实现ajax方法
下面是一个比较完整的Ajax
function ajax(){ var ajaxData =http://www.mamicode.com/ { type:arguments[0].type || "GET", url:arguments[0].url || "", async:arguments[0].async || "true", data:arguments[0].data || null, dataType:arguments[0].dataType || "text", contentType:arguments[0].contentType || "application/x-www-form-urlencoded", beforeSend:arguments[0].beforeSend || function(){}, success:arguments[0].success || function(){}, error:arguments[0].error || function(){} } ajaxData.beforeSend() var xhr = createxmlHttpRequest(); xhr.responseType=ajaxData.dataType; xhr.open(ajaxData.type,ajaxData.url,ajaxData.async); xhr.setRequestHeader("Content-Type",ajaxData.contentType); xhr.send(convertData(ajaxData.data)); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if(xhr.status == 200){ ajaxData.success(xhr.response) }else{ ajaxData.error() } } } } function createxmlHttpRequest() { if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { return new XMLHttpRequest(); } } function convertData(data){ if( typeof data =http://www.mamicode.com/== ‘object‘ ){ var convertResult = "" ; for(var c in data){ convertResult+= c + "=" + data[c] + "&"; } convertResult=convertResult.substring(0,convertResult.length-1) return convertResult; }else{ return data; } }
对比看下Jquery的Ajax
ajax({ type:"POST", url:"ajax.php", dataType:"json", data:{"val1":"abc","val2":123,"val3":"456"}, beforeSend:function(){ //some js code }, success:function(msg){ console.log(msg) }, error:function(){ console.log("error") } })
ajax({ type:"POST", url:"ajax.php", dataType:"json", data:{"val1":"abc","val2":123,"val3":"456"}, beforeSend:function(){ //some js code }, success:function(msg){ console.log(msg) }, error:function(){ console.log("error") } })
原生js实现ajax方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。