rpc.getUserInfo(function(result){
userdata = result;
}); //How can i get the value of "userdata"?
我尝试:JavaScript变量值
var userdata = "";
rpc.getUserInfo(function(result){
userdata = result;
});
alert(userdata); // it's "undefined"
rpc.getUserInfo(function(result){
userdata = result;
}); //How can i get the value of "userdata"?
我尝试:JavaScript变量值
var userdata = "";
rpc.getUserInfo(function(result){
userdata = result;
});
alert(userdata); // it's "undefined"
时间的一些假设:
Ajax是异步的,所以你不能进行Ajax调用,等待响应,然后运行调用该函数的下一行。
重写该脚本,以便在Ajax数据返回时执行的任何操作都在回调中完成,而不是在调用函数(即现在的位置)中完成。
错误:
var userdata = "";
rpc.getUserInfo(function(result){
userdata = result;
});
alert(userdata);
右:
rpc.getUserInfo(function(result){
alert(result);
});
你还没有说,但我猜getUserInfo
涉及一个异步 Ajax调用。既然如此,你不能使用内联值,你只能在回调中使用它。例如: -
rpc.getUserInfo(function(result){
var userdata;
userdata = result;
alert(userdata);
});
你只要把所有你将投入getUserInfo
呼叫后内回调,而不是逻辑的。这听起来很困难或尴尬,但使用JavaScript是很轻松:
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);
});
});
}
注意doSomething
回报之前,首先调用回调。
很显然,上面的匿名函数只适用于doSomething
的固有部分;否则,请将其功能移到单独的命名函数中。
猜对了!谢谢!我想我明白了! – TokkyLiu 2010-09-17 08:43:21
感谢您的帮助!你是对的 !大!!! – TokkyLiu 2010-09-17 08:40:23