I want to return StudentId
to use elsewhere outside of the scope of the $.getJSON()
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does
If you wish delegate to other functions you can also extend jquery with the $.fn. notation like so:
Even simpler than all the above. As explained earlier
$.getJSON
executes async which causes the problem. Instead of refactoring all your code to the$.ajax
method just insert the following in the top of your main .js file to disable the async behaviour:good luck!
Yeah, my previous answer does not work because I didn't pay any attention to your code. :)
The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:
Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
To accomplish scoping similar to C#, disable async operations and set dataType to json:
hmm, if you've serialized an object with the
StudentId
property then I think that it will be:But if you're just returning the
StudentId
itself maybe it's:Edit: Or maybe
.length
isn't even required (I've only returned generic collections in JSON).Edit #2, this works, I just tested:
Edit #3, here's the actual JS I used:
And in the aspx.vb: