functions.js
function clients(id){
var result = '';
$.ajax({
type: "GET",
url: "classes/response.php?type=clients",
data: {id: id},
success: function(data){
result = data;
console.log(result); // retrieves 'John'
console.log(data); // retrieves 'John'
}
});
return result;
}
在我的其他文件 main.js
中$("#client_check").on('click', function(){
var input = $("#client_id");
var name = clients(input.val());
console.log(name); // retrieves empty
$("#client_id").val('');
});
不应该这样吗?该函数完美地输出值,但是当我将函数调用到变量时,它检索为空。
我做错了什么?
答案 0 :(得分:0)
试试这个,我的更改只有callback
功能休息符合OP
function clients(id,callBack){
$.ajax({
type: "GET",
url: "classes/response.php?type=clients",
data: {id: id},
success: function(data){
result = data;
console.log(result); // retrieves 'John'
console.log(data); // retrieves 'John'
callBack(data);
}
});
}
$("#client_check").on('click', function(){
var input = $("#client_id");
clients(input.val(),function(name){
console.log(name);
});
$("#client_id").val('');
});
答案 1 :(得分:-1)
根据:How do I return the response from an asynchronous call?
解决function clients(id){
return
$.ajax({
type: "GET",
url: "classes/response.php?type=clients",
data: {id: id},
});
}
// And to call it:
clients(input.val()).done(function(r){
console.log(r);
});