我正在对get和getJSON进行jquery调用,但是无法访问回调函数之外的返回值.如何访问返回的数据?
var firstid;
var nextid;
$.get(callUrl, function(data) { // call to add node
var n = data.indexOf("id-");
var m = data.indexOf("id-");
firstid = data.substr(n+3,m - (n+3));
nextid = data.substr(m+3);
alert("firstid:" + firstid); // returns correct value
});
alert("firstid:" + firstid); // returns undefined for firstid
Run Code Online (Sandbox Code Playgroud)
我怎么能在功能之外得到第一次?
所有AJAX呼叫都是异步的
所以你需要使用回调.外面的任何东西都会回归undefined.
$.get(callUrl, function(data) { // call to add node
var n = data.indexOf("id-");
var m = data.indexOf("id-");
firstid = data.substr(n+3,m - (n+3));
nextid = data.substr(m+3);
doSomethingWithFirst(firstid);
});
function doSomethingWithFirst(f) {
//NOW do something
}
Run Code Online (Sandbox Code Playgroud)