Tengo debajo de la página HTML en la que aterrizo después de una autenticación exitosa. En su cuerpo, obtengo el valor access_token.
<html> <head> <title>Authorization successful</title> </head> <body> <p>Welcome. You are authorized to access the page.</p> <p>access_token: {{ access_token }}</p> <p>token_type: {{ token_type }}</p> <form method="POST" action="/protected_hi" > <button type="submit" id="protectedApiButton">Protected API</button> </form> <script src="ajax.js"></script> </body> </html>La página tiene un botón llamado "API protegida" en el que se registra el script ajax.js. ¿Cómo puedo obtener el valor de la variable access_token en mi script ajax.js?
let protectedApiButton = document.getElementById('protectedApiButton'); protectedApiButton.addEventListener('click', buttonClickHandler) function buttonClickHandler() { var myAttribute = <------------- how to assign access_token value from html template to here? console.log(myAttribute); const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://dummy.restapiexample.com/api/v1/create', false); xhr.setRequestHeader('Content-type', 'application/json'); xhr.onprogress = function(){ console.log('On progress'); } xhr.onload = function () { if(this.status === 200){ console.log(this.responseText) } else{ console.log("Some error occurred") } } params = `{"name":"ravi","age":"43"}`; xhr.send(params); }Agregue la entrada con el tipo oculto para almacenar el token de acceso.
<input type="hidden" id="access_token" value="token-goes-here" /> Luego recupere el valor de access_token en buttonClickHandler() :
function buttonClickHandler() { var myAttribute = document.getElementById('access_token').value; ... }