从回调函数返回 AJAX 结果
return ajax result from callback function
我有两个回调,其中一个应该返回布尔值,另一个应该做一个ajax调用。 但无法从第二个得到结果。
我已经阅读了一些有关如何从异步调用返回响应的说明,但无法获得任何结果。
有我的代码:
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;
}
}
}
你应该在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();
});
这是符合我最后一个答案的代码:
<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>
相关文章:
- 在foreach中获取ajax结果
- 使用blob从ajax结果下载文件
- PHP,MySQL,AJAX-调用AJAX结果后,Bootstrap CSS样式不会显示
- 在文本框中显示ajax结果
- 从回调函数返回 AJAX 结果
- 将AJAX结果作为道具传递给子组件
- 使用passthrough将ajax结果中的变量发送到php
- 等待ajax结果绑定淘汰模型
- 如何重置AJAX结果输入字段
- jquery不解析ajax结果
- 为什么我不能返回 $.ajax 结果,但可以返回 $http.post 的结果
- Javascript:将 AJAX 结果保存为 Class 变量
- Ajax 结果取决于 PHP 结果
- 在 ajax 结果中获取此内容
- 动态处理 ajax 结果
- 在视图页面上显示 AJAX 结果 jQuery
- Ajax 结果显示未定义
- 如何使用 AJAX 结果在点击功能
- 使用 jQuery 在 Ajax 结果中查找节点
- 返回到 ajax 结果页面上上次看到的位置