javascript原生ajax请求
class Ajax{ constructor(url, method, data, callback_suc, callback_err, callback_run){ this.RT = true;//默认为异步请求 this.url = url; this.method = method || "POST"; this.data = data || ""; this.callback_suc = callback_suc || function () {}; this.callback_err = callback_err || function () {}; this.callback_run = callback_run || function () {}; if(!this.url){this.callback_err(); return;} this.createRequest(); } createRequest(){ let xhr = new XMLHttpRequest(); xhr.onreadystatechange = (e)=>{this.run(e);} xhr.open(this.method, this.url, this.RT); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(this.data); } run(e){ this.callback_run(e); if(e.target.readyState !== 4 || e.target.status !== 200){return;} this.callback_suc(e); } } new Ajax(//调用 "./main.php", //url:请求地址 "POST", //method:请求方法 "data=3&sb=2",//data:传递数据 (e)=>{//callback_suc:请求完成 回调函数 document.write(e.target.responseText);//3 } (e)=>{}//callback_err:请求错误 回调函数 (e)=>{}//callback_run:请求中 回调函数 )
上面是js代码
下面以main.php为例接收请求
<?php //接收客户端请求数据data和sb $data = isset($_GET[‘data‘]) ? $_GET[‘data‘] : "data为空"; $sb = isset($_GET[‘sb‘]) ? $_GET[‘sb‘] : "sb为空"; //向客户端返回数据 echo $data." ".$sb; ?>
相关推荐
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
lyqdanang 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
李永毅 2020-07-05
坚持着执着 2020-07-05