停止执行jQuery函数

时间:2018-11-10 07:47:28

标签: jquery execution

我想要一个 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	
        }
    });
}

2 个答案:

答案 0 :(得分:1)

checksession的AJAX success回调成为执行“保存”操作(或不执行)的功能

//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
    //
}

答案 1 :(得分:0)

尝试一下:

 $("#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;

}