简体   繁体   English

jquery:为什么我不能在函数中返回boolean

[英]jquery: why i can't return boolean in function

i have current code: 我有当前的代码:

<button onclick="ismeloggedin()">

script: 脚本:

function ismeloggedin(){
    if(checkloggedin()){
        alert('you"re logged in');
    }else{
        alert('you didn"t login!!!!');
    }
}

function checkloggedin(){
    $.post('/test/check/',{'loggedin':0},function(data,status){
        return (data.status == 'error')?false:true; 
    });
}

php is not necessary but post anyway php是没有必要的,但无论如何发布

function check(){
    is(isset($_POST['loggedin'])){
        if(isLoggedIn()){
            $json = ['status'=>'success'];
        }else{
            $json = ['status'=>'error'];
        }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($json);
    }
}

i got the issue is checkloggedin() this function return undefined 我得到的问题是checkloggedin()这个函数返回undefined

instead return true/false 而是返回true / false

jQuery's post function is asynchronous . jQuery的post函数是异步的 That means that your function is returning before the data is loaded, so there is no way to get that value back to the original function. 这意味着您的函数在加载数据之前返回,因此无法将该值恢复为原始函数。

You'll have to re-think the structure of your code, remembering that the data will not be immediately available. 您将不得不重新考虑代码的结构,记住数据不会立即可用。 For example, when the page loads you could send the request, then when it completes (ie when your inner function is called) you can modify content on the page accordingly. 例如,当页面加载时您可以发送请求,然后当它完成时(即调用内部函数时),您可以相应地修改页面上的内容。

function GenerateResult(pResult){
    if(pResult){
        alert('you\'re logged in');
    }else{
        alert('you didn\'t login!!!!');
    }
}

function ismeloggedin(){
    $.post('/test/check/',{'loggedin':0},function(data,status){
        GenerateResult((data.status == 'error')?false:true);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM