ajout
This commit is contained in:
38
WIM4.1/tp/tp3/ex2/index.html
Normal file
38
WIM4.1/tp/tp3/ex2/index.html
Normal file
@@ -0,0 +1,38 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="stylesheet" href="http://www.iut-fbleau.fr/css/tacit.css">
|
||||
<title>Ajax</title>
|
||||
<script src="js/serviceAjax.js"></script>
|
||||
<script src="js/helpers.js"></script>
|
||||
|
||||
</head>
|
||||
<body container>
|
||||
<form action="">
|
||||
<fieldset>
|
||||
<label for="">Commune</label>
|
||||
<input autocomplete=off list="communes" type="text">
|
||||
<datalist id="communes"></datalist>
|
||||
<button type="submit">Envoyer</button>
|
||||
</fieldset>
|
||||
</form>
|
||||
</body>
|
||||
<script>
|
||||
let doRequest = debounce (search,500)
|
||||
let input = document.querySelector("input")
|
||||
let listes = document.querySelector("datalist")
|
||||
input.addEventListener("input",doRequest)
|
||||
|
||||
let cache = []
|
||||
async function search(ev){
|
||||
|
||||
let communes_promise = http.getVilles(input.value);
|
||||
|
||||
communes_promise.then(function(table) {
|
||||
autocomplete(listes, table);
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
</html>
|
19
WIM4.1/tp/tp3/ex2/js/helpers.js
Normal file
19
WIM4.1/tp/tp3/ex2/js/helpers.js
Normal file
@@ -0,0 +1,19 @@
|
||||
function debounce(fn, wait)
|
||||
{
|
||||
let timeout;
|
||||
return (...args) => {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => fn(...args), wait);
|
||||
}
|
||||
}
|
||||
function autocomplete(datalist,communes)
|
||||
{
|
||||
// À compléter
|
||||
datalist.innerHTML = '';
|
||||
|
||||
for(let c of communes) {
|
||||
let option = document.createElement("option");
|
||||
option.value = c;
|
||||
datalist.appendChild(option);
|
||||
}
|
||||
}
|
30
WIM4.1/tp/tp3/ex2/js/serviceAjax.js
Normal file
30
WIM4.1/tp/tp3/ex2/js/serviceAjax.js
Normal file
@@ -0,0 +1,30 @@
|
||||
let http={
|
||||
getVilles(nom){
|
||||
// À compléter
|
||||
let final_json;
|
||||
return fetch('https://geo.api.gouv.fr/communes?nom=' + nom + '&fields=departement&boost=population&limit=7')
|
||||
.then(readResponseAsJson)
|
||||
.then(function(body) {
|
||||
final_json = new Array();
|
||||
body.forEach(el => final_json.push(el.nom));
|
||||
return final_json
|
||||
})
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
function readResponseAsJson(response){
|
||||
|
||||
if (!response.ok) {
|
||||
|
||||
console.log(response.statusText);
|
||||
}
|
||||
|
||||
else {
|
||||
return response.json()
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user