2017年4月24日 星期一

【Javascript】兩視窗資料傳遞的方法

這幾天遇到一個需求,必須另開視窗產生完超商代收的 barcode 資訊,
再回傳相關資訊給原本視窗,接下來再 POST 所有資訊到下一頁,
在這邊記錄一下問題的大致做法。

主流程:

<button type="button" onclick="genBarcode();>超商代收</button>
<script>
  function genBarcode() {
    var frmPay = document.getElementById("payInfo");
    frmPay.target = "POPUP";
    frmPay.action = "barcode.jsp";

    var popup = window.open("", "POPUP", "height=300,width=400");
    if (popup) {
      frmPay.submit();
    }
  }

  function nextStep(barcode) {
    var frmPay = document.getElementById("payInfo");
    frmPay.target = "";
    frmPay.action = 'nextStep.php';

    field = document.createElement('input');
    field.type = 'text';
    field.name = 'barcode';
    field.value = barcode;
    frmPay.appendChild(field);
    frmPay.submit();
  }
</script>

另開視窗頁面:

<script>
  var barcode = Math.random();
  document.getElementById("barcode").value = barcode;
  window.opener.nextStep(barcode);
</script>

沒有留言:

張貼留言