[英]Why Javascript global variable is not global?
我有一個外部js文件處理刪除一些元素。 根據結果,我將確定是否需要刷新頁面。
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
});
沒問題,我無法更改在jQuery事件處理程序中deleted
的全局變量。 我可以確保刪除操作成功,但是此變量不會將其值更改為1。
為什么?
Ajax是異步的,因此它將在執行if else
檢查之后設置deleted
變量。 嘗試將檢查放入回調中。
$("#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;
});
我修復了異步設置為同步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.