Soy novato en AJAX. Mi objetivo es abrir en JavaScript un archivo php.
function checkCorrect(userEntry, solution) {
return fetch("checkSolution.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: `userEntry=${userEntry}&solution=${solution}`,
})
.then((response) => response.text())
.then((res) => (res))
.catch(err => console.log("checkCorrect: " + err));
}
function checkSolution() {
result = checkCorrect(userEntry, solution);
alert(result)
}
Solución del problema
De hecho, fetch es asíncrono. no lo sabía En mi caso, estoy buscando un método síncrono.
XMLHttpRequest es el enfoque correcto en mi caso.
Y aquí está la solución:
function checkCorrect(userEntry, solution) {
var ret_value = null;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
ret_value = xmlhttp.responseText;
}
}
xmlhttp.open("POST","checkSolution.php",false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("userEntry="+userEntry+"&solution="+solution);
return ret_value;
}
No hay comentarios.:
Publicar un comentario