How do i get access to the data return from jquery ajax call. Outside the $.ajax( ).
//Reloads the inital page
function jobexist( jobname )
{
var dataString = 'jobname=' + jobname;
var found = false;
$.ajax(
{
type: 'POST',
url: "/genode/jobs/jobexist.m",
data: dataString,
dataType: 'json',
success: function(data)
{
alert("Passed");
if( data.result == 0 )
{
found = true;
}else{
found = false;
}
},
error: function( data )
{
alert("Login Failed");
return -1; //alert(data);
}
});
if( found == true )
{
alert("found!")'
开发者_开发百科 return true;
}else{
alert("not found!");
return false;
}
}
if( !jobexist(jobname) )
{
$("#jobname_error").text("This jobname already exist.");
$("#jobname_error").show();
return false;
}
Ajax works asynchronously so your if found statement will be hit before the ajax call finishes.
What you can do is call a function from inside your ajax success function and pass whatever data you want to it
function found(data){
if( data.result == 0 )
{
alert("found!")
return true;
}else{
alert("not found!");
return false;
}
}
$.ajax(
{
type: 'POST',
url: "/genode/jobs/jobexist.m",
data: dataString,
dataType: 'json',
success: function(data)
{
alert("Passed");
found(data);
},
error: function( data )
{
alert("Login Failed");
return -1; //alert(data);
}
});
JavaScript is asynchronous, which means you should change your way of thinking a bit, and start mind-twisting journey into the strange world of callbacks and closures. You could simply expose some variable outside of your ajax call scope, and assign data to it, but it's not really what you want to do.
What you want to do is:
define a callback function:
function afterAjax() { $("#jobname_error").text("This jobname already exist."); $("#jobname_error").show(); return false; };
redefine your function responsible for ajax to accept callbackFn as a second parameter:
function jobexist( jobname, callbackFn ) {
pass your callback function when executing ajax-responsible function:
jobexist(jobname, afterAjax)
execute this callback when the time is right:
if( data.result == 0 ) { callbackFn(); }
精彩评论