Repository navigation
Expand file tree
/
Copy pathmyajax.html
More file actions
76 lines (71 loc) · 2.05 KB
/
Copy pathmyajax.html
File metadata and controls
76 lines (71 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>
<script>
function ajax(obj){
//初始化数据
if(typeof(obj)!=="object"){console.log("请传入json");return;}
var url=obj.url; //传入地址
if(url==undefined){console.log("请传入正确的url");return;}
var method=obj.type||"get"; //传输方式
var async=obj.async==undefined?"true":obj.async; //同异步传输
var datatype=obj.datatype||"text"; //得到数据的类型
var data=""; //传入的数据
var success=obj.success; //运行成功后执行的函数
//检测数据类型存入data
var tpof=typeof(obj.data)
if(tpof=="string"){data=obj.data;}
if(tpof=="object"){
for(var i in obj.data){
data+=i+"="+obj.data[i]+"&";
}
data=data.slice(0,-1);
}
//判断传输方式
var ajax=window.XMLHttpRequest? new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(method=="get"){
ajax.open("get",url+"?"+data,async);
ajax.responseType=datatype;
ajax.send(null);
}else if(method=="post"){
ajax.open("post",url,async);
ajax.responseType=datatype;
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(data);
}
//检测数据是否交换成功
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
var result;
//数据交换成功后,取出数据存入result
if(datatype=="xml"){result=ajax.responseXML}else{result=ajax.response}
if(success){
success(result);
}
}else if(ajax.status==404){
console.log("页面没有找到");
}else{
console.log("获取错误");
}
}
}
}
ajax({
url:"2.15.xml",
type:"get",
async:"true",
datatype:"xml",
data:{aa:"bb",cc:"dd"},
success:function(e){
console.log(e)
}
})
//ajax("dssd")
</script>