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

259
Views
La solicitud E6 Ajax no funciona

Tengo una secuencia de comandos en la que quiero obtener algunos datos json de un punto final, pero aparece un error, esta es mi secuencia de comandos:

 function httpGet(url) { return new Promise( function (resolve, reject) { var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (this.status === 200) { // Success resolve(this.response); } else { // Something went wrong (404 etc.) reject(new Error(this.statusText)); } } request.onerror = function () { reject(new Error( 'XMLHttpRequest Error: '+this.statusText)); }; request.open('GET', url); request.send(); }); } var url = 'https://api.jsonPlaceholder.com'; httpGet(url) .then(JSON.parse) .then((r) => { console.log(r); }).catch(function(error) { console.log(error); });

Luego, en la consola arroja un error:

Error en XMLHttpRequest.request.onreadystatechange (app.js:11) en app.js:18 en Promise () en httpGet (app.js:2) en app.js:25

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

No puede simplemente verificar status , debe verificar readyState == 4 antes de poder decidir qué sucedió:

 function httpGet(url) { return new Promise( function (resolve, reject) { var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (this.readyState === 4) { // *** if (this.status === 200) { // Success resolve(this.response); } else { // Something went wrong (404 etc.) reject(new Error(this.statusText)); } } // *** } request.onerror = function () { reject(new Error( 'XMLHttpRequest Error: '+this.statusText)); }; request.open('GET', url); request.send(); }); }

La especificación dice que acceder a this.response antes de que se complete la solicitud debería devolver una cadena vacía, pero para mí, usando Chrome v57, al hacerlo, aparece el error que citó. Agregar la verificación readyState lo soluciona.

over 4 years ago · Santiago Trujillo Report
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!