在函数之后延迟window.open()

时间:2016-04-06 16:39:48

标签: javascript mysql ajax

我有这个insertData()函数保存到DB并根据数据库的条目显示window.open() 所以这是我的尝试,

function(isConfirm){
    if (isConfirm) {
        insertData();
        window.open("../../../html/reports/cashreceipt_print.php?sr_record="+sr_id);
    } else {
        swal("CANCELLED", "", "error");
    }
});

function insertData(){
    $.ajax({
        type: 'POST',
        url: "../../../html/main/divpages/submit_data.php",
        data: sentReq,
        dataType: 'JSON',
        success: function (response, textStatus, jqXHR) {
            if (response.indexOf("GAGAL") == -1) {
                window.location.href = "main.php";
            } else {
                alert("GAGAL INSERT");
            }
        }
    });
}

所以当新窗口打开时,这里的问题,sr_record =大部分时间都没有显示在该弹出窗口中。将插入SR_RECORD并打开窗口将调用刚插入insertData()的SR_ID。我能找到最适合我的解决方案。请帮帮我

2 个答案:

答案 0 :(得分:1)

insertData是AJAX,A代表异步,所以它在你调用window.open时没有完成,使用你拥有的成功函数或使用jquery的.done方法:

$.ajax({
  url: "test.html",
  context: document.body
}).done(function(data) {
  // do your 'data' stuff here
});
$.ajax({
    type: 'POST',
    url: "../../../html/main/divpages/submit_data.php",
    data: sentReq,
    dataType: 'JSON',
    success: function (response, textStatus, jqXHR) {
       // your sr.id is hopefully on the response object( if its being sent back properly.
    }
});

答案 1 :(得分:0)

好的解决方案就是这么简单,我首先打开弹出窗口然后发送回main.php

function insertData(){
            $.ajax({
                type: 'POST',
                url: "../../../html/main/divpages/submit_data.php",
                data: sentReq,
                dataType: 'JSON',
                success: function (response, textStatus, jqXHR) {
                    if (response.indexOf("GAGAL") == -1) {
                        window.open("../../../html/reports/cashreceipt_print.php?sr_record="+sr_id);
                        window.location.href = "main.php";
                    } else {
                        alert("GAGAL INSERT");
                    }
                }
            });
        }