iT邦幫忙

0

jquery於兩個視窗間傳值的問題

請教各位前輩,ajax有没有可能做到以下的傳值情況:

(一)先於瀏覽器開啟兩個視窗,一個執行A.php,一個執行B.php
(二)於A.php click一個按鈕後,利用ajax post一個json值給B.php
(三)B.php在不重新執行的情況下,能接收此JSON值,並於網頁上呈現

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
dragonH
iT邦超人 5 級 ‧ 2019-05-03 11:47:04
最佳解答

單純看兩個視窗互傳值的話

可以用 postMessage

不過有一些限制就是

不是隨便兩個視窗都能互傳

給個範例

a.html

<!DOCTYPE html>
<html>
  <head>
    <title>A</title>
  </head>
  <body>
    <div class = "box">
      <button type = "button" id = "newWindow">開新視窗</button>
      <textarea id = "toSay"></textarea>
      <button id = "sendText">送出文字</button>
      <button id = "sendJson">送出json</button>
    </div>
  </body>
  <script>
    const newWindowBtn = document.getElementById('newWindow');
    const sendTextBtn = document.getElementById('sendText');
    const sendJsonBtn = document.getElementById('sendJson');
    let targetWindow = null;
    newWindowBtn.addEventListener('click', () => {
      targetWindow = open('./b.html');
    });
    sendTextBtn.addEventListener('click', () => {
      const toSayText = document.getElementById('toSay').value;
      if (targetWindow) {
        targetWindow.postMessage(toSayText, '*');
      } else {
        alert('請先開新視窗');
      }
    });
    sendJsonBtn.addEventListener('click', () => {
      if (targetWindow) {
        targetWindow.postMessage({ name1: 'apple', name2: 'banana' }, '*'); 
        // '*' 代表允許所有targetOrigin
      } else {
        alert('請先開新視窗');
      }
    });    
  </script>
</html>
<style>
  .box{
    display: flex;
    justify-content: center;
    justify-items: center;
  }
</style>

b.html

<!DOCTYPE html>
<html>
  <head>
    <title>B</title>
  </head>
  <script>
    window.addEventListener('message', (msg) => {
      let node = document.createElement('p');
      node.textContent = `${new Date()} : ${JSON.stringify(msg.data)}`;
      document.getElementById('receiveDiv').append(node)
    });
  </script>
  <body>
    <div id = "receiveDiv"></div>
  </body>
</html>

透過 a.html 開啟 b.html

就能從 a 傳到 b

也能 b 傳到 a (用 window.opener.postMessage())

不過就像樓上說的

如果b.php 是想要取得a.php執行更新後的資料的話

大部分的情況應該還是用websocket等那些方法

0
淺水員
iT邦大師 6 級 ‧ 2019-05-02 17:47:24

這很類似聊天室,一般的方法是用輪詢的方式
也就是說 B.php 定時會從伺服器取得更新的資料
這方法可能稍微有點時間差
但是比較容易實現

另外還有SSE(Server-Sent Events)、長輪詢(long polling)、websocket 等方法
這三種可以即時更新

1

其實你有一個觀念上錯誤的問題。

首先,你不了解何謂ajax的東西。
ajax相關解釋可以自行google看一下。我這邊就用很單純的理解說明給你。

ajax你可以將其視為開一個瀏覽器物件,或是開一個href。但它跟我們原本的url中的href的方式不太相哃。
其就是在原瀏覽器上,直接背景式運做處理。
要用白話一點來說,就是跟後端請求或處理程式碼。

但你要的是在在一個已經顯示的視窗中「傳值」的情況。然後打算用ajax本身就是一個大錯誤。

一般來說,依你的需求來說,也不能說用ajax不對。只是並不能說是a頁面傳到b頁面這樣的說法。這不是ajax能做到且也是破壞它原本機制的東西。

換另外一種做法就是
a->ajax->傳後端
b->ajax->取後端

可是這樣子就會變成有一個問題,b並無法得知a是什麼情況下需要取後端資料。
所以就有了websocket這樣的用法出現。
用白話點來說,就是b會固定監視著後端。有新的資料就處理。
用法就自行查看一下吧。

不過 dragonH 教你的方式,對你來說會比較直覺。這是視窗之間傳值的方式。
一般來說,依性質而言。如果不需要記錄資料的情況下。
其實用視窗之間的傳送就好了。

zzhsu20 iT邦新手 5 級 ‧ 2019-05-07 15:32:29 檢舉

感謝浩瀚星空兄的回覆,有時觀念上的提點是很重要的教學,感謝。

我要發表回答

立即登入回答