设置var并立即返回新值

时间:2013-01-10 09:59:55

标签: javascript jquery

我遇到了一个问题,我会做这样的事情

var abc = false;
function doSomthing(){
abc = true;
return abc;
}

并返回false,但如果我运行该函数两次(在控制台中),则第二次返回true。

由于

原始功能

var session_id_resualt = false;

function islogdin() {
    if (localStorage.email == undefined) {
        localStorage.email = "";
    }

    if (localStorage.session_id == undefined) {
        localStorage.session_id = "";
    }

    $.post(server + "loginCheck.php", {
        loginCheck: "",
        cookie: readCookie("h"),
        session_id: localStorage.session_id,
        email: localStorage.email
    },

    function (json) {
        json = $.parseJSON(json);
        if (json.logdin) {
            if (json.logdin == "1") {
                //var s_id = json.session_id;
                session_id_resualt = json.session_id;
                //return s_id;          
            } else {
                session_id_resualt = false;
                //  return false;
            }

        } else {
            session_id_resualt = false;
            //  return false;
        }
    });
    return session_id_resualt;

}

1 个答案:

答案 0 :(得分:0)

$.post是异步的。你需要等待结果。但是,由于$.post没有提供更改$.ajax设置的简单方法,因此您必须使用$.ajax代替async: false

var data = {
    loginCheck: "",
    cookie: readCookie("h"),
    session_id: localStorage.session_id,
    email: localStorage.email
};

var url = server + "loginCheck.php";

var callback = function (json) {
    /* ... */
}

$.ajax({
    type: "POST",
    url: url,
    async: false, /* importan! */
    data: data,
    success: callback,
});

参考文献: