停止 jQuery 函数执行

Stop jQuery function from executing

我想要一个 save 函数来检查是否设置了会话(使用另一个函数)并停止基本函数继续,但该函数似乎继续(下面不可执行) ):

//1. Base save function

$("#save").click(function (e) {    
  e.preventDefault();
  //step 0 check if logged in
  checksession();
  console.log("teststop"); //just for testing
  //steps x continue execution of session exists
});

//2. Session check function
function checksession(){ 
    $.ajax({ 
 type: "GET",
 url:"xxxx/sessioncheck.php",
 dataType: "text",
 cache: false,
 success: function(data){
     if(data == "no"){
  return;
            } else {} //continue 
        }
    });
}

checksession的AJAXsuccess回调成为执行"save"操作(或不执行)的函数

//1. Base save function

$("#save").click(function (e) {             
  e.preventDefault();
  //step 0 check if logged in
  checksession();
});


//2. Session check function

function checksession(){    
    $.ajax({ 
    type: "GET",
    url:"xxxx/sessioncheck.php",
    dataType: "text",
    cache: false,
    success: function(data){
            if(data == "no")
            {
                console.log( "stop" );
            } else {
                console.log( "continue" ); 
                doSave();
            }   
        }
    });
}


//3. Perform save operation

function doSave() {
    //
    // proceed with the save operation
    //
}

试试这个:

 $("#save").click(function (e) {    


  e.preventDefault();
  //step 0 check if logged in
  check();
if(check()==true){
continue;
}else{
stop
}
  console.log("teststop"); //just for testing
  //steps x continue execution of session exists
});

//2. Session check function
function check(){
var result=false;
    function checksession(){    
        $.ajax({ 
        type: "GET",
        url:"xxxx/sessioncheck.php",
        dataType: "text",
        cache: false,
        success: function(data){
            if(data == "no"){
            return;
                } else {
result=true;
} //continue    
            }
        });
    }
return result;

}