JavaScript variable value
rpc.getUserInfo(function(result){
userdata = result;
}); //How can i get the value of "userdata"?
I try:
var userdata = "";
rpc.getUserInfo(function(result){
userdata = re开发者_JAVA百科sult;
});
alert(userdata); // it's "undefined"
Time for some assumptions:
- RPC usually stands for Remote Procedure Call
- This suggests you are performing Ajax
- A standard pattern for Ajax functions is to accept a callback function which runs when the call is complete.
Ajax is Asynchronous, so you can't make an Ajax call, wait for the response, then run the next line of the function that made the call.
Rewrite the script so that whatever you want to do when the Ajax data comes back is done in the callback and not in the function that makes the call (which is where it is now).
Wrong:
var userdata = "";
rpc.getUserInfo(function(result){
userdata = result;
});
alert(userdata);
Right:
rpc.getUserInfo(function(result){
alert(result);
});
You haven't said, but I'm guessing that getUserInfo
involves an asynchronous ajax call. That being the case, you can't use the value inline, you can only use it in the callback. E.g.:
rpc.getUserInfo(function(result){
var userdata;
userdata = result;
alert(userdata);
});
You just put all of the logic that you would have put after the getUserInfo
call inside the callback instead. That sounds difficult or awkward, but with JavaScript it's trivially easy:
function doSomething() {
var foo;
// Do some setup
foo = 42;
// Here's our first asynchronous call; like all good asynchronous calls,
// it accepts a function to call when it's done
triggerAjaxCall("mumble", function(bar) {
// Now the first call is complete, we can keep processing
// Note that we have access to the vars in our enclosing scope
foo += bar;
// Need to do another asynchronous call
triggerSomeOtherAjaxCall(foo, function(nifty) {
// Now the second call is complete and we can keep working with
// all of our stuff
alert("foo: " + foo + "\n" +
"bar: " + bar + "\n" +
"nifty: " + nifty);
});
});
}
Note that doSomething
returns before the first callback is called.
Obviously the anonymous functions above are only appropriate if they're an intrinsic part of doSomething
; otherwise, move their functionality into separate named functions.
精彩评论