0

There are some postings about getting the returned value of the get-call. But my problem is still there.

My source

...
$.get("list.svc/XmlTestService", function (XmlData) { console.log(XmlData); }, "xml");
...
alert($Loc['Name']);
...

I get an XML-Document which is correct at the console. Normaly I have to proceed with the Xml to do something. This will be done in a separate function like this:

function GetOutXml (XmlData) {
  ...
  return { 'Name': ValueName }
}

Now I need to close my gap between my get-call and the alert. I tried some different things but without success. One way was something like this:

...
var $Xml = null;
$.get("list.svc/XmlTestService", function (XmlData) { $Xml = XmlData; }, "xml");
var $Loc = GetOutXml($Xml);
...

But without success. I´m new with the World of JS (only basics). Normaly I build my source with an functional architecture.

How can I do this right?

Update: Okay...I solved my problem in a other way after reading a lot. Because to do every thing in anonymous function is not my way of thinking and it´s hard to read and follow after time.

So what I did:

...
var $Xml = null;
$.ajax({type:'GET',url:"list.svc/XmlTestService",success: function(Data) { $Xml = Data;},dataType:'xml',async:false});
...
var $Loc = GetOutXml($Xml);
...

The important step is to do the job with the ajax-command because of the posibility to set async to false so it is sync.

Thanks for helping me.

2 Answers2

2

Ajax is asynchronous -- the get call starts the process, but it finishes later. So your code after the call runs before your code in the callback. (The "callback" is the function you pass into get. "callback" is a generic term for a function that gets "called back" later in response to something. Event handlers are also callbacks, although oddly we rarely call them that.)

What you want to do is actually do your work in the callback:

$.get("list.svc/XmlTestService", function (XmlData) {
    // Use XmlData here
}, "xml");

That may seem alien, but it will soon be very familiar.

So for instance, suppose you had code that looked like this and isn't working;

// This doesn't work
var a, b;
var $Xml;
a = doSomething();
b = /* ...some other thing... */;
$.get("list.svc/XmlTestService", function (XmlData) {
    $Xml = XmlData;
}, "xml");
if (a > b) {
    doSomethingWithXml($xml);
}
else {
    doADifferentThingWith($xml);
}

That changes to look like this:

// This does work
a = doSomething();
b = /* ...some other thing... */;
doSomething();
$.get("list.svc/XmlTestService", function ($Xml) {
    if (a > b) {
        doSomethingWithXml($xml);
    }
    else {
        doADifferentThingWith($xml);
    }
}, "xml");
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0
$.get("list.svc/XmlTestService", GetOutXml, "xml");

function GetOutXml (XmlData) {
  ...
  return { 'Name': ValueName }
}

is what you need?

vladkras
  • 16,483
  • 4
  • 45
  • 55