-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.html
81 lines (75 loc) · 1.92 KB
/
promise.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="./libs/js/main.js"></script>
<script type="text/javascript">
//https://qiita.com/natsuki_summer/items/50a2f5981f757dfe81c7
const apiKey = 'ucC12wVgsngvVL8gxokroFuHSgMgvgem5ZTL3LnA';
const apiUrl = "https://opendata.resas-portal.go.jp/api/v1/";
let ajaxPrefProp = {
url:apiUrl + 'prefectures',
type:'GET',
headers:{
'X-API-KEY':apiKey
}
}
let ajaxCityProp = {
url:apiUrl + "cities",
type:'GET',
headers:{
'X-API-KEY':apiKey
}
}
function getPref() {
return new Promise((resolve, reject) => {
$.ajax(ajaxPrefProp).done((data) => {
//成功時
resolve(data)
}).fail((data) => {
//失敗時
reject(data)
})
})
}
function getShiku(pref_val) {
return new Promise((resolve, reject) => {
ajaxCityProp['data'] = {
'prefCode':pref_val
}
$.ajax(ajaxCityProp).done((data) => {
resolve(data)
}).fail((data) => {
reject(data)
})
})
}
//Promise使用時
getPref()
.then((data) => {
if (data['result'] !== undefined) {
let length = data['result'].length
for(var i = 0; i < length; i++) {
if (data['result'][i]['prefName'] == '千葉県') {
$('#pref_area').html(data['result'][i]['prefName'] + ':' +data['result'][i]['prefCode'])
return getShiku(data['result'][i]['prefCode'])
}
}
}
}).then((data) => {
//多段プロミス
let length = data['result'].length
let cityStr = ''
for(var i = 0; i < length; i++) {
cityStr += data['result'][i]['cityName'] + '<br>'
}
$('#city_area').html(cityStr)
},(err, msg) => {
console.log('サーバーとの通信に失敗しました。')
})
</script>
<body>
<div id="pref_area"></div>
<div id="city_area"></div>
</body>
</html>