是否可以在jquery get
function doSomething() {
var level;
$.get('http://example.com/getLevel', {
'login': user
},
function (resp) {
//any way to access user or assign resp to level here?
level = resp; //does not work here.
});
//at this point level is still undefined.
}
由于
答案 0 :(得分:1)
Ajax是异步的,这就是为什么在代码中的注释点未定义级别的原因。如果您需要将响应分配给level
并使用该变量,则必须在成功处理程序中包含该代码。
目前,在ajax调用返回响应之前,会执行尝试使用level(在ajax调用之后编写的代码)的代码。这会导致level
未定义。
function doSomething() {
var level;
var data = {'login':user}; //assigning data outside of get invocation
$.get('http://example.com/getLevel', data,function(resp){
//any way to access user or assign resp to level here?
level = resp; //does not work here.
//at this point level is defined and should be used in the code.
});
//data could now be used here
}
答案 1 :(得分:1)
How to return the response from an AJAX call 会告诉您我在这里说的内容。请在线查看评论
function doSomething() {
var level;
var data = {
'login': user
};
$.get('http://example.com/getLevel', data, function (resp) { // js dont wait (Thats why called Asynchronous JavaScript and XML) for this request to complete and immediately executed next line of code.This is called callback function where your code gets executed after you receice responce from AJAX call.
level = resp;
// you can use level here
callback(resp); // // Or use callback function and pass it response once you receive it.
});
// Here it could be possible that your your response is no yet received so your level variable still undefined.
}
function callback(level) {
// use level here
}