1+ function ajax ( options ) {
2+ options = options || { } ; //调用函数时如果options没有指定,就给它赋值{},一个空的Object
3+ options . type = ( options . type || "GET" ) . toUpperCase ( ) ; /// 请求格式GET、POST,默认为GET
4+ options . dataType = options . dataType || "json" ; //响应数据格式,默认json
5+
6+ var params = formatParams ( options . data ) ; //options.data请求的数据
7+
8+ var xhr ;
9+
10+ //考虑兼容性
11+ if ( window . XMLHttpRequest ) {
12+ xhr = new XMLHttpRequest ( ) ;
13+ } else if ( window . ActiveObject ) { //兼容IE6以下版本
14+ xhr = new ActiveXobject ( 'Microsoft.XMLHTTP' ) ;
15+ }
16+
17+ //启动并发送一个请求
18+ if ( options . type == "GET" ) {
19+ xhr . open ( "GET" , options . url + "?" + params , true ) ;
20+ xhr . send ( null ) ;
21+ } else if ( options . type == "POST" ) {
22+ xhr . open ( "post" , options . url , true ) ;
23+
24+ //设置表单提交时的内容类型
25+ //Content-type数据请求的格式
26+ xhr . setRequestHeader ( "Content-type" , "application/x-www-form-urlencoded" ) ;
27+ xhr . send ( params ) ;
28+ }
29+
30+ // 设置有效时间
31+ setTimeout ( function ( ) {
32+ if ( xhr . readySate != 4 ) {
33+ xhr . abort ( ) ;
34+ }
35+ } , options . timeout )
36+
37+ // 接收
38+ // options.success成功之后的回调函数 options.error失败后的回调函数
39+ //xhr.responseText,xhr.responseXML 获得字符串形式的响应数据或者XML形式的响应数据
40+ xhr . onreadystatechange = function ( ) {
41+ if ( xhr . readyState == 4 ) {
42+ var status = xhr . status ;
43+ if ( status >= 200 && status < 300 || status == 304 ) {
44+ options . success && options . success ( xhr . responseText , xhr . responseXML ) ;
45+ } else {
46+ options . error && options . error ( status ) ;
47+ }
48+ }
49+ }
50+ }
51+
52+ //格式化请求参数
53+ function formatParams ( data ) {
54+ var arr = [ ] ;
55+ for ( var name in data ) {
56+ arr . push ( encodeURIComponent ( name ) + "=" + encodeURIComponent ( data [ name ] ) ) ;
57+ }
58+ arr . push ( ( "v=" + Math . random ( ) ) . replace ( "." , "" ) ) ;
59+ return arr . join ( "&" ) ;
60+
61+ }
62+
63+
0 commit comments