原生js实现ajax方法(超简单)
上一篇文章写到原生js取代jquery的一些常用函数:原生js仿jquery一些常用方法,那么,ajax如何实现呢?如下是一个比较完整的ajax()
function ajax(){ var ajaxData = { 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 === '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") } })
相关推荐
lyqdanang 2020-08-16
坚持着执着 2020-06-16
TONIYH 2020-06-05
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07