How to make javascript wait until it gets a valid response from synchronous http request? -
i know not idea use synchronous requests case need it.
i have tried make getenddate
function calling if response lenght less 20 after first unsuccessfull request (if url gives short response) goes alert(enddate.eddayow);
, getting error, , getenddate
continues sending request every 500 ms.
i need getenddate
function continue sending request until valid response , return valid object, , after continue next line of js. how achieve that?
var url = 'http://local.com/cgi-bin/hello2.pl'; // url returns plain text: // 1234567890 2013 05 may friday 13 23 45 01 var enddate = getenddate(url); alert(enddate.eddayow); function getenddate(url) { var xmlhttp = getxmlhttp(); xmlhttp.open('get', url, false); xmlhttp.send(); if (xmlhttp.status == 200 && xmlhttp.responsetext.length > 20) { var n = xmlhttp.responsetext.split(" "); return { 'edseconds': n[0], 'edyear': n[1], 'edmon': n[2], 'edmonname': n[3], 'eddayow': n[4], 'edday': n[5], 'edhour': n[6], 'edmin': n[7], 'edsec': n[8] }; } else { settimeout("getenddate(" + url + ")", 500); } } function getxmlhttp() { var xmlhttp; try { xmlhttp = new activexobject("msxml2.xmlhttp"); } catch (e) { try { xmlhttp = new activexobject("microsoft.xmlhttp"); } catch (e) { xmlhttp = false; } } if (!xmlhttp && typeof xmlhttprequest != 'undefined') { xmlhttp = new xmlhttprequest(); } return xmlhttp; }
i don't know if satisfies requirement, rewrite this:
var enddate; getenddate(url); function do_rest(returndate) { enddate = returndate; alert(enddate.eddayow); // more if need }; function getenddate(url) { var xmlhttp = getxmlhttp(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4) { if (xmlhttp.status == 200 && xmlhttp.responsetext.length > 20) { var n = xmlhttp.responsetext.split(" "); do_rest({ 'edseconds': n[0], 'edyear': n[1], 'edmon': n[2], 'edmonname': n[3], 'eddayow': n[4], 'edday': n[5], 'edhour': n[6], 'edmin': n[7], 'edsec': n[8] }); } else { settimeout("getenddate(" + url + ")", 500); } } } xmlhttp.open('get', url, false); xmlhttp.send(); }
Comments
Post a Comment