js进阶ajax函数封装(匿名函数作为参数传递)(封装函数引入文件的方式非常好用)

js进阶ajax函数封装(匿名函数作为参数传递)(封装函数引入文件的方式非常好用)

一、总结

2、匿名函数作为参数传递

二、js进阶ajax函数封装

ajax1.js

 1 function ajax(url,funSucc,fnFaild){ //1、以函数作为函数的参数传进来
 2 
 3     var xhr=new XMLHttpRequest();
 4 
 5     xhr.open('GET',url,true);
 6 
 7     xhr.send(null);
 8 
 9     xhr.onreadystatechange=function(){
10 
11         if (xhr.readyState==4) {
12 
13             if (xhr.status==200) {
14 
15                 funSucc(xhr.responseText) //2、使用传进来的函数
16 
17 
18             }else{
19                 if (fnFaild){
20                      fnFaild(xhr.statusText)
21                 }
22 
23             }
24         }
25     }
26 
27 }

html测试代码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>ajax01</title>
 6     <style type="text/css">
 7         div{
 8           background: green;
 9            300px;
10           height: 200px;
11         }
12     </style>
13     <script type="text/javascript" src="ajax1.js"></script>  //1、引入js
14 </head>
15 <body>
16     <input type="button" id="btn" value="测试按钮">
17     <div id="div1"></div>
18     <script>
19     var btn=document.getElementById('btn');
20     var div1=document.getElementById('div1');
21     btn.onclick=function (){
22         ajax('test1.txt',function(str){ //2、匿名函数作为参数传过去
23             div1.innerHTML=str
24         },function(s){
25             alert(s)
26         })
27     }
28     </script>
29 </body>
30 </html>
原文地址:https://www.cnblogs.com/Renyi-Fan/p/9062290.html