Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
Ejecutando una página PHP desde AJAX y esperando los resultados

Soy bastante nuevo en Javascript. Me gustaría usar Javascript para ejecutar un script PHP en el servidor y capturar el resultado (que son algunos elementos de texto CSV) y luego usar ese resultado para actualizar mi página web.

Ya tengo una función Javascript genérica para ejecutar una página PHP, que es esta:

 function executePhpPage(url) { // executes a PHP page try { httpxml = new XMLHttpRequest(); httpxml.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { return httpxml.responseText; } } httpxml.open("GET", url, true); httpxml.send(null); } catch (e) { alert(e.message); } }

Sin embargo, el control se devuelve a la persona que llama cuando el hilo de ejecución sale de la parte inferior de la función, antes de que se devuelvan los resultados. Por lo tanto, he intentado modificarlo a esto:

 function sleep(ms) { // see https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep return new Promise(resolve => setTimeout(resolve, ms)); } function executePhpPage(url) // returns the results of the page { // executes a PHP page and returns the results try { httpxml = new XMLHttpRequest(); httpxml.open("GET", url, true); httpxml.send(null); while (!(this.readyState == 4 && this.status == 200) ) { sleep(10); } return httpxml.responseText; } catch (e) { alert(e.message); } }

La llamada a la función es:

 var host = window.location.protocol + "//" + window.location.host; var url = host + "/AJAX_NewsletterSubscribe.php?email=" + cEmail + "&download=1"; alert(url); results = executePhpPage(url); alert(results);

'''alerta (resultados)''' nunca se alcanza, la página web se vuelve inactiva y tengo que eliminarla desde el administrador de tareas. Presumiblemente, está dando vueltas alrededor del sueño repetidamente.

¿Cómo puedo esperar hasta que lleguen los resultados antes de devolver la ejecución de executePhpPage y devolver los datos resultantes?

Preferiría respuestas en Javascript directo en lugar de JQuery o cualquier cosa si es posible. Gracias.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!