如果頁面有 Ajax,記得先把 async 設為 false 讓請求同步執行,確保後續流程能拿到結果:
var countdownInterval;
/* 確認立即充值 */
function ToRecharge() {
var paramData = new Object();
paramData.PayType = 1; // 支付寶支付
paramData.OrderMoney = parseFloat($("#spShouldPay").text()); // 支付總金額
var gprsTel = [];
var orderDetail = new Array();
for (var i = 0; i < deviceList.length; i++) {
orderDetail[i] = new Object();
orderDetail[i].DeviceSN = deviceList[i].DeviceSN; // 設備 SN 碼
orderDetail[i].GPRSTel = deviceList[i].GPRSTel; // GPRS 手機號碼
orderDetail[i].PayYear = parseInt($("#hdnYear").val());
orderDetail[i].PayPotency = 100; // 暫時默認兩百元
gprsTel.push(deviceList[i].GPRSTel);
}
paramData.GPRSTel = gprsTel.join(",");
paramData.OrderDetail = $.toJSON(orderDetail);
paramData.rand = Math.random();
paramData.PostType = "AddRecharge";
$.ajax({
url: '/App_Ajax/Service.ashx',
data: paramData,
type: 'post',
async: false, // 使 Ajax 同步
success: function (resultData) {
var jsonResult = $.parseJSON(resultData);
if (!jsonResult.success) {
window.$.messager.alert('提示', "充值記錄保存失敗!");
newwindow.close();
return;
}
$("#backupdate").text("返回修改");
$("#timerecharge").hide();
$("#onrecharge").show();
$("#rechargesuccess").hide();
$("#hdnOrderStatus").val(jsonResult.obj.OrderStatus);
$("#hdnOID").val(jsonResult.obj.OID);
// 啟動輪詢,不斷讀取 Recharge_Order 表的 OrderStatus,成功則停止
CheckOrderStatus(jsonResult.obj.OID);
// 以 POST 方式開啟新視窗
openPostWindow(
String.format("https://{0}/Default/Service/Recharge.aspx", location.host),
$.toJSON(jsonResult.obj),
"_blank"
);
}
});
}
window.open 只支援 GET,無法帶 body。要在新視窗中送出 POST 資料,標準做法是動態產生一個 form、設定 target 為 _blank,把資料放進隱藏欄位後送出:
/* POST 開啟新窗口 */
function openPostWindow(url, data, target) {
var tempForm = document.createElement("form");
tempForm.id = "tempForm1";
tempForm.method = "post";
tempForm.action = url;
tempForm.target = target;
var hideInput = document.createElement("input");
hideInput.type = "hidden";
hideInput.name = "PostName";
hideInput.value = data;
tempForm.appendChild(hideInput);
document.body.appendChild(tempForm);
tempForm.submit();
document.body.removeChild(tempForm);
}
至於「讓 window.open 在同一分頁開啟」,關鍵在第三個參數:把 target 設為 "_self" 即可取代當前頁面;設 "_blank" 才是新分頁。
第一,async: false 是同步 Ajax,它會凍結整個瀏覽器 UI 直到回應返回,現代瀏覽器已在主執行緒上發出 deprecation 警告,正式環境請改用 async 搭配 Promise/callback 串接流程。
第二,新式寫法可以直接用 window.open(url, '_self') 做同頁跳轉,或直接 location.href = url;若需要帶 POST,除了上面的動態表單法,也可以考慮 sessionStorage 暫存資料、新視窗開啟後再取出,避免把資料塞進隱藏欄位。另外別忘了 tempForm 是全域變數時應宣告 var,以免污染全域。