ajaxFunction = function(lastNumber){
var json_result = '';
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"first" : "'+lastNumber+'"}',
url: "http://localhost:8080/some_url",
success: function (result) {
console.log("in success: " + result.result);
json_result = result.result;
}
});
console.log("before return " + json_result);
return json_result;
};
答案 0 :(得分:1)
问题是返回结果,然后调用的ajax执行异步。
以下是使用Deferred替换的示例。
return value from nested function in jquery
function test(){
var def = new $.Deferred();
$.ajax({
url: 'test',
success: function(data) {
// Do some minor logic to determine if server response was success.
console.log('success in callback');
if(data == true){
def.resolve(true);
}
else{
def.reject();
// or possibly def.resolve(true) depending what you're looking for.
}
},
error:function(){
console.log('error in callback');
def.reject();
}
});
return def;
}
编辑:您的案例:
var ajaxFunction = function(lastNumber){
var def = new $.Deferred();
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"first" : "'+lastNumber+'"}',
url: "http://example.com",
success: function (result) {
console.log("in success: " + result.result);
def.resolve(result.result);
},
error: function(){
def.reject();
}
});
return def;
};
var testMethod = function(){
var result = ajaxFunction('some number');
result.done(function(result){
alert(result);
console.log('done in deferred');
// Do something when everything went well.
}).fail(function(){
alert('error');
console.log('error in deferred');
// Do something when something went bad.
});
}
testMethod();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
你可以把它拿来试试
ajaxFunction = function(lastNumber){
var json_result = '';
$.ajax({
async: false,
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"first" : "'+lastNumber+'"}',
url: "http://localhost:8080/some_url",
success: function (result) {
console.log("in success: " + result.result);
json_result = result.result;
}
});
console.log("before return " + json_result);
return json_result;
};
当您将async设置为false时,它会使调用同步,默认情况下为true。
如果不使用这个,你可以使用回叫或承诺(工作和返回,如同步调用)。
答案 2 :(得分:0)
始终使用$.Deferred()
对象并在Ajax调用中返回它。
在.resolve()
Ajax调用回调中使用.success()
到您的延迟变量。
调用您的方法并使用延迟函数的.done
方法进行检查。