I'm trying to make my javascript code more dynamic, so I've made an Ajax request class that takes the requesturl as a parameter through the constructor and sends the response back through a method getResponse.
I'm using onreadystate in asynchronous mode. I've read on a forum that it's the best way.
My problem is that I can't figure out how to check when onreadystate is completed... Since it's asynchronous it calls the function getResponse before the request is completed...
Please give me some hints!!!!
Code:var reqObj = new AjaxRequest("http://localhost:8080/AjaxProject/autoGetCities.do?city=b"); var r = reqObj.getResponse(); console.log("Finished" + r.resposeText); function AjaxRequest(urlStr){ var req; var status = "false"; this.initRequest = initRequest; this.doRequest = doRequest; this.getResponse = getResponse; this.onreadystate = onreadystate; this.doRequest(urlStr); function doRequest(url){ req = this.initRequest(); req.open("GET", url, true); req.onreadystatechange = onreadystate; req.send(null); } function getResponse(){ if(status=="true"){ return req; }else{ return null; } } function onreadystate(){ if (req.readyState == 4) { if (req.status == 200) { if( req.responseText.length > 0){ status = "true"; } }else if (req.status == 204){ this.clearTable(); } } } function initRequest() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } } }
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks