标签:传递 end request ext php sse for his 回调函数
1 class Ajax{ 2 3 constructor(url, method, data, callback_suc, callback_err, callback_run){ 4 this.RT = true;//默认为异步请求 5 this.url = url; 6 this.method = method || "POST"; 7 this.data = data || ""; 8 this.callback_suc = callback_suc || function () {}; 9 this.callback_err = callback_err || function () {}; 10 this.callback_run = callback_run || function () {}; 11 if(!this.url){this.callback_err(); return;} 12 this.createRequest(); 13 } 14 15 createRequest(){ 16 let xhr = new XMLHttpRequest(); 17 xhr.onreadystatechange = (e)=>{this.run(e);} 18 xhr.open(this.method, this.url, this.RT); 19 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 20 xhr.send(this.data); 21 } 22 23 run(e){ 24 this.callback_run(e); 25 if(e.target.readyState !== 4 || e.target.status !== 200){return;} 26 this.callback_suc(e); 27 } 28 29 } 30 31 new Ajax(//调用 32 "./main.php", //url:请求地址 33 "POST", //method:请求方法 34 "data=3&sb=2",//data:传递数据 35 (e)=>{//callback_suc:请求完成 回调函数 36 document.write(e.target.responseText);//3 37 } 38 (e)=>{}//callback_err:请求错误 回调函数 39 (e)=>{}//callback_run:请求中 回调函数 40 )
上面是js代码
下面以main.php为例接收请求
1 <?php 2 //接收客户端请求数据data和sb 3 $data = isset($_GET[‘data‘]) ? $_GET[‘data‘] : "data为空"; 4 $sb = isset($_GET[‘sb‘]) ? $_GET[‘sb‘] : "sb为空"; 5 //向客户端返回数据 6 echo $data." ".$sb; 7 ?>
标签:传递 end request ext php sse for his 回调函数
原文地址:https://www.cnblogs.com/weihexinCode/p/12316696.html