douyong1974 2016-05-26 12:49
浏览 209

如何在xhr请求完成之前暂停javascript脚本?

I have made a script that allows the user to send a weekly newsletter powered by php. My php code is fine and working 100%. However, i made a script to count how many newsletters have been send out to check if all the newsletters have been send.

The code i made is the following:

function sendMail(test) {
var onderwerp = document.getElementById('getOnderwerp').value;
var pin = document.getElementById('secretPIN').value;
var e = document.getElementById('selectBrief');
var brief = e[e.selectedIndex].value;
var checkbox = [];
$('input[type="checkbox"][name="check_list[]"]').each(function(_, ele) {
if ($(ele).prop('checked')) {
   checkbox.push($(ele).attr('value'));
  }
});
loadgif2();

var breakx = false;
var temp = '';
var text = '';
var h = 0;
var regExp = /\(([^)]+)\)/;
var xhr = [];

for(var j = 0; j < checkbox.length; j++) {

    if (breakx == true) {
        removegif();
        break;
    }


    var provincie = checkbox[j].replace(/\(([^)]+)\)/, '');
    var aantal = checkbox[j].match(regExp)[1];

    h = 0;

    xhr = [];

    temp = '';
    temp = provincie + ' word verstuurd';
    text += temp + '<br>';


    for (i = 0; i < aantal; i++) {
        if (breakx == true) {
            break;
        }
        (function (i) {
            xhr[i] = new XMLHttpRequest();
            url = "/modules/pages/ajax/nieuwsbrief/send-mail.php?provincie=" + provincie +
                "&test=" + test + "&brief=" + brief + "&onderwerp=" + onderwerp + "&pin=" + pin + "&offset=" + i;
            xhr[i].open("POST", url, true);
            xhr[i].onreadystatechange = function () {
                if (xhr[i].readyState == 4 && xhr[i].status == 200) {



    document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
     document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                        h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;

                    h++;
                    if (h == aantal) {
                        text = text.replace(temp, provincie + ' is verzonden<br>');
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
                    } else {
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                        h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
                    }

                    console.log(xhr[i].responseText);

                    if (xhr[i].responseText == '<br> Ongeldige PIN') {
                        breakx = true;
                    }

                }
            };
            xhr[i].send();
        })(i);
    }
}
}

The code above is working but the only problem i'm facing is that as soon as i have a checkbox array length > 1 it'll not work properly. My guess is that the loop is going too fast and the xhr request just takes a little more time to get the php file stuff. My question is here how am i going to fix this? I was thinking myself to pause the script until the xhr requrest was done and resume it after.

Edit

I have edited my code to be like this:

    function sendMail(FormElements, test) {
    var onderwerp = document.getElementById('getOnderwerp').value;
    var pin = document.getElementById('secretPIN').value;
    var e = document.getElementById('selectBrief');
    var brief = e[e.selectedIndex].value;
    var checkbox = [];
    $('input[type="checkbox"][name="check_list[]"]').each(function(_, ele) {
    if ($(ele).prop('checked')) {
       checkbox.push($(ele).attr('value'));
      }
});
loadgif2();

    sendmail2(0, test,brief,onderwerp,pin,checkbox, '');
}

function sendmail2(checkboxcount, test,brief,onderwerp,pin,checkbox,text) {
    var breakx = false;
    var temp = '';
    var h = 0;
    var regExp = /\(([^)]+)\)/;
    var xhr = [];
    var provincie = checkbox[checkboxcount].replace(/\(([^)]+)\)/, '');
    var aantal = checkbox[checkboxcount].match(regExp)[1];

    temp = provincie + ' word verstuurd';
    text += temp + '<br>';
    for (i = 0; i < aantal; i++) {
        if (breakx == true) {
            break;
        }
        (function (i) {
            xhr[i] = new XMLHttpRequest();
            url = "/modules/pages/ajax/nieuwsbrief/send-mail.php?provincie=" + provincie +
                "&test=" + test + "&brief=" + brief + "&onderwerp=" + onderwerp + "&pin=" + pin + "&offset=" + i;
            xhr[i].open("POST", url, true);
            xhr[i].onreadystatechange = function () {
                if (xhr[i].readyState == 4 && xhr[i].status == 200) {
                    document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
                    document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                        h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;

                    h++;
                    if (h == aantal) {
                        text = text.replace(temp, provincie + ' is verzonden<br>');
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
                        if (checkboxcount + 1 == checkbox.length) {

                        } else {
                            sendmail2(checkboxcount + 1, test, brief, onderwerp, pin, checkbox,text);
                        }
                    } else {
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                            h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
                    }

                    console.log(xhr[i].responseText);

                    if (xhr[i].responseText == '<br> Ongeldige PIN') {
                        breakx = true;
                    }

                }
            };
            xhr[i].send();
        })(i);


    }
    }

This code acutally works the way i want to, but now i'm gettting some random 500 internal errors, but they seem to be completely random? sometimes they appear and sometimes they don't and i'm not changing anything. any solutions to this?

  • 写回答

1条回答 默认 最新

  • doutizha7526 2016-05-26 12:57
    关注

    At your code:

    xhr[i].open("POST", url, true);
    

    Change it to:

    xhr[i].open("POST", url, false);
    

    It is a deprecated and bad workaround for your problem, you should find an other way. ( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests )

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。