gpt4 book ai didi

javascript - $.post函数可以覆盖父函数中的变量吗

转载 作者:行者123 更新时间:2023-11-28 21:20:54 25 4
gpt4 key购买 nike

上周我开始使用 JavaScript,所以我的知识......非常有限。请耐心等待我:-)

我正在编写一个简单的预订系统,该系统在 MySql 中存储日期和用户 ID。它检查给定日期是否已被预订(如果是,则 isTicket.php 返回 UserId,如果仍然空闲则返回 0)。由于可以选择一个日期范围,并且我不想发送多个警告,所以如果在任何选定的日期内其他用户已经预订,我将变量 otherEventFound 设置为 false。

如下所示,我尝试在后函数的“外部”使用此变量,有两种可能性:

1) 如果我的脚本包含行 >>alert ("otherEventFound... << 它有效。

2)如果我删除此行,则不会。

我有点迷失方向了。有人可以解释为什么这个额外的警报行如此重要,更一般地说,是否可以从 post.success 函数覆盖父函数中的变量?

如果这纯粹是运气,而不是与警报线一起使用,那么在 JavaScript 中执行此操作的正确方法是什么?

parent function
...
var otherEventFound = new Boolean();
var do_the_booking = new Boolean();
otherEventFound = false;
do_the_booking = false;
for ( var i = myStart.getDfJ(); i <= myEnd.getDfJ(); i++)
{
// conver i to MySQL format yyyy-mm-dd
var milliseconds = 1000 * 60 * 60 * 24 *i;
var j = new Date(milliseconds);
var strID = j.toYMD();
// and ask server if there is other event on this day
$.post("isTicket.php", { theDay: strID },
function(answ){
if ( parseInt(answ) == 0 ){
do_the_booking = true;
}
else {
if ( !(parseInt(answ) == currentUserId) ){
otherEventFound = true;
}
}
}
);
}

alert ("otherEventFound " + otherEventFound + " do_the_booking " + do_the_booking);

if (otherEventFound==true) {
alert ("There is not yours event booked on this day.");
do_the_booking=false;
};
if (do_the_booking==true){
var x=window.confirm("Do you want to book on this/these day/s?")
if (x) {
// ... do something like $.post("setTicket.php" ...
}
}

最佳答案

当您执行 $.post 时,会启动一个异步 AJAX 请求,该请求稍后会回调您的内联函数。由于您不希望在返回固定数量的异步请求之前执行某段代码,因此您必须跟踪已完成的请求数量。

它与警报一起“工作”的唯一原因是警报会插入一个暂停,直到您应答为止,此时 AJAX 调用已完成并执行内联函数。

您基本上想像这样修改代码:

var otherEventFound = false;
var do_the_booking = false;

var completeRequests = 0;
for ( var i = myStart.getDfJ(); i <= myEnd.getDfJ(); i++)
{
// do something

// and ask server if there is other event on this day
$.post("isTicket.php", { theDay: strID },
function(answ){
completeRequests++;
if ( parseInt(answ) == 0 ){
do_the_booking = true;
}
else {
if ( !(parseInt(answ) == currentUserId) ){
otherEventFound = true;
}
}

if (completeRequests == myEnd.getDfJ()) {
postProcessing();
}
}
);
}

function postProcessing() {
alert ("otherEventFound " + otherEventFound + " do_the_booking " + do_the_booking);

if (otherEventFound==true) {
alert ("There is not yours event booked on this day.");
do_the_booking=false;
};
if (do_the_booking==true){
var x=window.confirm("Do you want to book on this/these day/s?")
if (x) {
// ... do something like $.post("setTicket.php" ...
}
}
}

关于javascript - $.post函数可以覆盖父函数中的变量吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6433864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com