[英]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.