开发者

Why JavaScript global variable is not global?

I have a external js file handling deleting some element. According to the result, I would determine whether I need to refresh the page or not.

var deleted = 0; // first assume not deleted 

$(function() {
    $("#action a.action-delete").click(function() {
        var id = $(this).parent().parent().attr("id");
        $.get("modify-sale.php", { "id" : id, "action" : "delete" }, function (data) { deleted = 1;  }, "text");
        if (deleted) return true; // if success then refresh
        else return false; // else does not refresh
    });

No the probl开发者_运维知识库em is I could not change the global variable deleted in the jQuery event handler. I can assure that the delete action is success, but this variable just does not change its value to 1.

Why?


Ajax is asynchronous, so it will set the deleted variable after you do the if else check. Try putting the check in the callback.


$("#action a.action-delete").click(function() {
    var id = $(this).parent().parent().attr("id");
    $.ajax({
        "url" :  "modify-sale.php",
        "type" : "GET",
        "data" : { "id" : id, "action" : "delete" },
        "dataType" : "text",
        "async" : false,
        "success" : function(data) {
            if (data == 'success') {
                $("#msg").text("delete success").show();
                $("#msg").fadeOut(1000);
                deleted = 1;
            } else {
                $("#msg").text("delete failed, plesase try later").show();
                $("#msg").fadeOut(5000);
            }
        },
        "error" : function() {
            $("#msg").text("delete failed, please try later").show();
            $("#msg").fadeOut(5000);
        }
    });
    if (deleted) return true;
    else return false;
});

I fixed it with the async set to synchronized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜