am_dot_com

SW 2023-05-17

May 17th, 2023 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.44 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <!-- API = Application Programming Interface
  6. para nos provarmos autorizados a fazer pedidos à API
  7. teremos que identificar-nos através de uma string
  8. que teremos que obter,
  9. => https://home.openweathermap.org/api_keys <=
  10. que se diz "a nossa API key"
  11.  
  12. -->
  13. <!--
  14. Técnica AJAX
  15. é uma solução para criar pedido entre
  16. um "cliente"
  17. e um "servidor", disponível num
  18. qualquer endereço em rede.
  19. O pedido, tipicamente, é feito "assincronamente",
  20. o que é significa que é "não bloqueante",
  21. o que signifca que, por exemplo, numa seq
  22. de instruções JS, o código não fica parada não
  23. instrução que executa o pedido (segue para as instruções
  24. seguintes).
  25. Mas podemos escolher pedidos bloqueantes.
  26.  
  27. i1;
  28. valor = i2(); -> imaginar que a i2 é async
  29. // se i2 for async, avançamos para i3
  30. // sem garantia de terminação de i2
  31. i3; // não podemos garantir que valor exista
  32.  
  33. Como lidar com código async?
  34. Uma solução comum é usar o conceito de "callback"
  35.  
  36. -->
  37. <title>Técnica AJAX - aplicada a openweathermap.org</title>
  38. <script src="am_ajax.js"></script>
  39. <script src="am_util.js"></script>
  40. <script src="1.js"></script>
  41. </head>
  42. <body>
  43. <form id="idFormOWM">
  44. <label for="idLocations">Localizações pré-definidas:</label>
  45. <select id="idLocations">
  46. <option>Portugal,Santarém</option>
  47. <option>Itália,San Marino</option>
  48. <option>Portugal,Lisbon</option>
  49. </select>
  50. <input type="submit" value="obter info">
  51. </form>
  52. <hr>
  53. <section id="idSectionResponse">
  54.  
  55. </section>
  56. </body>
  57. </html>
  58.  
  59. **********************
  60.  
  61. function ajaxGet(
  62. pUrlApiEndpoint, // https://openweathermap.org/api/s1
  63. pWhereToWriteTheResponse, // objeto onde escrever a resposta, quando chegar
  64. pDoAsync=true
  65. ){
  66. var req = new XMLHttpRequest()
  67.  
  68. if(req){
  69. req.open(
  70. "GET",
  71. pUrlApiEndpoint,//destino
  72. pDoAsync
  73. )
  74.  
  75. /*
  76. o pedido passa por estágios
  77. de "maturidade"
  78. 1 - emitido
  79. 2 - recebido
  80. 3 - resposta sendo preparada
  81. 4 - resposta pronta
  82.  
  83. no código abaixo
  84. "maturityHandler" é o nome de uma
  85. função JS que será
  86. AUTOMATICAMENTE chamada
  87. sempre que houver mudança
  88. no estado de maturidade
  89.  
  90. (representada em readyState)
  91. */
  92. req.onreadystatechange = maturityHandler
  93.  
  94. // prototipagem (prop criada agora)
  95. req.oWhereToWriteTheResp = pWhereToWriteTheResponse
  96.  
  97. req.send(null)
  98.  
  99. return true
  100. }//if
  101. return false
  102. }//ajaxGet
  103.  
  104. function ajaxPost(
  105. pUrl,
  106. pForm, // representa uma form
  107. pWhereToReply,
  108. pAsync
  109. ){
  110. var req = new XMLHttpRequest()
  111. if(req){
  112. req.open(
  113. "POST",
  114. pUrl,
  115. pAsync
  116. )
  117. req.oWhereToWriteTheResp = pWhereToReply
  118. req.onreadystatechange = maturityHandler
  119.  
  120. var theData = new FormData(pForm)
  121. req.send(theData)
  122.  
  123. return true
  124. }
  125. return false
  126. }//ajaxPost
  127.  
  128. function maturityHandler(){
  129. //this representa o pedido
  130. //permite acesso a todas as props nativas (como readyState)
  131. //e outras, que tenhamos acrescentado
  132. //por conveniência, por prototipagem
  133. var bRequestReady = this.readyState===4 // && this.code===200
  134. if(bRequestReady){
  135. //apenas e tão somente quando o pedido estar totalmente pronto
  136. //veremos a resposta
  137. var theResponse = this.responseText
  138. this.oWhereToWriteTheResp.innerHTML = theResponse
  139.  
  140. //escrever esta function em cada projeto específico
  141. processResponse(theResponse)
  142. }
  143. //enquanto o pedido não estiver pronto, aparece o output do código abaixo
  144. else{
  145. this.oWhereToWriteTheResp.innerHTML = ""+
  146. `request current state: ${this.readyState}`
  147. }
  148. }//maturityHandler
  149.  
  150. ************************
  151.  
  152. //1.js
  153. window.onload = boot
  154.  
  155. //https://home.openweathermap.org/api_keys
  156. MY_KEY = "A TUA API KEY AQUI"
  157.  
  158. /*
  159. q=Lisboa,Portugal
  160. appid=MY_KEY
  161. */
  162.  
  163. const OWMAP_BASE_URL =
  164. "https://api.openweathermap.org/data/2.5/weather?"
  165.  
  166. function buildRequest(
  167. pLocal,
  168. pApiKey=MY_KEY
  169. ){
  170. var strLocal = encodeURIComponent(pLocal)
  171. var strReq = `${OWMAP_BASE_URL}q=${strLocal}&appid=${pApiKey}`
  172. return strReq
  173. }//buildRequest
  174.  
  175.  
  176. const ID_FORM_OWM = "idFormOWM",
  177. ID_LOCATIONS = "idLocations",
  178. ID_SECTION_RESPONSE = "idSectionResponse"
  179. var oFormOWM, oLocations, oSectionResponse;
  180.  
  181. function boot(){
  182. oFormOWM = id(ID_FORM_OWM)
  183. oLocations = id(ID_LOCATIONS)
  184. oSectionResponse = id(ID_SECTION_RESPONSE)
  185.  
  186. oFormOWM.onsubmit = goGetResponse
  187. }//boot
  188.  
  189. function goGetResponse_v1(){
  190. //window.alert("hello")
  191. var url = buildRequest(
  192. oLocations.value,
  193. MY_KEY
  194. )
  195. oSectionResponse.innerHTML = url
  196. return false
  197. }
  198.  
  199. function processResponse(pR){
  200. //como processar a resposta
  201. oResponse = JSON.parse(pR)
  202. var latitude = oResponse['coord']['lat']
  203. window.alert(latitude)
  204. }//processResponse
  205.  
  206. function goGetResponse(){
  207. var url = buildRequest(
  208. oLocations.value,
  209. MY_KEY
  210. )
  211. ajaxGet(
  212. url,
  213. oSectionResponse,
  214. true
  215. )
  216. return false
  217. }
Advertisement
Add Comment
Please, Sign In to add comment