jQuery return ajax success function results
I need to return true or false to my alert() from the results of an ajax success function. However, I'm having problems since the alert() result is always 'undefined'...any ideas on how to fix this?
I have DoAjax
as it's own function because I call it multiple times within the .js file.
var val = '12345';
alert( DoSerialVerification( val ) ); //this returns 'undefined' 开发者_运维技巧regardless of cType.length
function DoSerialVerification( piVal ){
var fSuccess = function( oData ){
var cType = oData.type
if( cType.length > 0 ){
alert( cType ); //with piVal = 12345 cType will return 'MODULE'
$('#dialog-1').attr('type', cType);
return true;
} else {
return false;
}
};
DoAjax({ Action: "DoSerialVerification", Value: piVal }, fSuccess );
}
function DoAjax( pAjaxParams, pSuccess ){
$.ajax({url : 'procedures?',
data : pAjaxParams,
async : false,
type : "POST",
dataType : "json",
error : function(oD,oT,oE){ alert( oD+'\n'+oT+'\n'+oE ) },
success : pSuccess
});
}
you need to return something from the DoSerialVerification function... modified DoSerialVerification function:
function DoSerialVerification( piVal ){
// here
var result = false;
var fSuccess = function( oData ){
var cType = oData.type
if( cType.length > 0 ){
alert( cType ); //with piVal = 12345 cType will return 'MODULE'
$('#dialog-1').attr('type', cType);
//here
result = true;
}
};
DoAjax({ Action: "DoSerialVerification", Value: piVal }, fSuccess );
//here
return result;
}
What you're trying to do isn't possible: calling AJAX is an asynchronous process, your function DoAjax will return before the response is ever received from the server. That is why you are providing callbacks: once the server returns a response, it'll enter either your error callback or your success callback, depending on the result.
Change this:
alert( DoSerialVerification( val ) );
To this:
DoSerialVerification(val);
And then move your alert call into your "fSuccess" function.
精彩评论