Page 1 of 1

Sending control back to calling function in XMLHttpRequest

Posted: Sun Aug 28, 2005 4:42 am
by anjanesh

Code: Select all

var req;

function foo()
 {
        loadXMLDoc("myurl.com/myxml.xml");
        // Nothing to be done until xml file is 100% loaded
        DoSomething_Next();
 }

function loadXMLDoc(url)
 {
        req = false;

        if (window.XMLHttpRequest)
         {
                try { req = new XMLHttpRequest(); }
                catch(e) { req = false; }
         }
        else if (window.ActiveXObject)
         {
                try { req = new ActiveXObject("Msxml2.XMLHTTP"); }
                catch(e) 
                 {
                        try { req = new ActiveXObject("Microsoft.XMLHTTP"); }
                        catch(e) { req = false; }
                 }

         }

        if(req)
         {
                req.onreadystatechange = processReqChange;
                req.open("GET", url, true);
                req.send("");
         }
 }

function processReqChange()
 {
        if (req.readyState == 4) 
         {   
                if (req.status == 200)                 
                        // Return back to foo() - continue from line after loadXMLDoc call
                else                 
                        // Error                 
         }
 }
Any way to send control back to line containing DoSomething_Next(); when req.status = 200 ?

Thanks

Posted: Sun Aug 28, 2005 7:58 am
by feyd
you should be able to just return, or exit the function call in some fashion and it should go back. Only a script level error would stop execution, typically.

Posted: Sun Aug 28, 2005 8:04 am
by anjanesh
I have one loadXMLDoc() function and one processReqChange() function.
But there may be many ways to call loadXMLDoc() on the same page. So loadXMLDoc() may be called twice - a situation where the second time the function is called is when the first xml file is being dwonloaded.

In that case in processReqChange(), how will I know where to send back to ?

Code: Select all

if (req.status == 200) 
 // Send to ....where ?
Its possible that the fist xml file is being downloaded while the second one is fiished.

Posted: Sun Aug 28, 2005 8:51 am
by feyd
Javascript knows the call stack, it should be just fine. Have you tested it? You're not allowed to set the execution pointer.

It would appear your code only supports a single XMLHTTP query at a time anyways.

Posted: Sun Aug 28, 2005 9:06 am
by anjanesh
You mean I should change

Code: Select all

req.onreadystatechange = processReqChange;
to

Code: Select all

req.onreadystatechange = function ()
 {
 };
?

Posted: Sun Aug 28, 2005 9:15 am
by feyd
I was actually referring to the "req" object.