/
weather.html
59 lines (58 loc) · 1.19 KB
/
weather.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function ajax(opts){
var url = opts.url
var type = opts.type || "GET"
var dataType = opts.dataType || "json"
var onsuccess = opts.onsuccess || function(){}
var onerror = opts.onerror || function(){}
var data = opts.data || {}
var dataStr = []
for(var key in data){
dataStr.push(key + "=" + data[key])
}
dataStr = dataStr.join("&")
if(type === "GET"){
url += "?" +dataStr
}
var xhr = new XMLHttpRequest()
xhr.open(type,url,true)
xhr.onload = function(){
if((xhr.status >=200 && xhr.status <300) || xhr.status ==304){
if(dataType ==="json"){
onsuccess(JSON.parse(xhr.responseText))
}else{
onsuccess(xhr.responseText)
}
}else{
onerror()
}
}
xhr.onerror = onerror
if(type === "POST"){
xhr.send(dataStr)
}else{
xhr.send()
}
}
ajax({
url: 'http://api.jirengu.com/weather.php',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret)
},
onerror: function(){
console.log('服务器异常')
}
})
</script>
</body>
</html>