我有两个回调,其中一个应该返回布尔值,另一个做一个ajax调用。但无法从第二个获得结果。
我已经阅读了一些关于如何return the response from an asynchronous call但无法获得任何结果的解释。
有我的代码:
if( $.fn.wizard ) {
$('#wzd-enrollment').wizard({
//some code
onStepLeave: function (wizard, step){
//in this function i have always to return a boolean value to move to the next step or not
var result;
result = doAjax(wizard, step);
console.log(result); //always log undefined
return result;
}
});
function doAjax(wizard, step){
if(step.id == 'step-1' ){
//some code
$.ajax({
type: "GET",
dataType: 'json',
url: s_url,
}).done(function( data ) {
//some code
return true;
}).fail(function(jqXHR, textStatus, errorThrown){
//some code
return false;
});
}else{
return true;
}
}
}
答案 0 :(得分:0)
您应该在document.ready上执行doAjax功能。 步骤休假没有必要这样做。
检查以下代码
var s_url = ''; // fill out your url here
// save the result in a var
var resultStep1 = true;
if( $.fn.wizard ) {
$('#wzd-enrollment').wizard({
//some code
onStepLeave: function (wizard, step){
var result2 = false;
return checkResult(step);
}
});
}
function doAjax(){
//some code
$.ajax({
type: "GET",
dataType: 'json',
url: s_url,
}).done(function( data ) {
//some code
resultStep1 = true;
}).fail(function(jqXHR, textStatus, errorThrown){
//some code
resultStep1 = false;
});
}
function checkResult(step) {
if(step.id == 'step-1' ){
return resultStep1;
}
else {
return true;
}
}
// get the result on page load
$(document).ready(function() {
doAjax();
});
答案 1 :(得分:0)
这是符合我最后答案的代码:
<input type="button" value="Next" id="wizard_next_button" style="display: none" />
<input type="button" value="Next" id="your_next_button" style="display: block" />
<script>
var s_url = ''; // fill out your url here
// save the result in a var
var result = true;
if( $.fn.wizard ) {
$('#wzd-enrollment').wizard({
//some code
onStepLeave: function (wizard, step){
return result;
}
});
}
function doAjax(callback){
if($("#wizard").steps("getCurrentIndex") == 'step-1' ){
//some code
$.ajax({
type: "GET",
dataType: 'json',
url: s_url,
}).done(function( data ) {
//some code
if ( typeof(callback) == 'function' ) {
callback(true);
}
}).fail(function(jqXHR, textStatus, errorThrown){
//some code
if ( typeof(callback) == 'function' ) {
callback(false);
}
});
} else {
if ( typeof(callback) == 'function' ) {
callback(true);
}
}
}
// get the result on page load
$("#your_next_button").click(function() {
doAjax(function(retval) {
result = retval;
$("#wizard_next_button").trigger('click');
});
});
</script>