簡體   English   中英

在父頁面中加載 AJAX,允許訪問子頁面中的變量

[英]Load AJAX in parent page, give access to variables in child pages

我有一個包含一系列 iframe 的父頁面。 這些都駐留在同一個域中。

我有一個 AJAX 調用,該調用在每個 iframe 加載時運行,它為我檢索了一些 JSON 用於填充駐留在其中的輸入。 每個 iframe 檢索的信息相同。

目前,我正在每個 iframe 內部運行 AJAX 調用。 這並沒有讓我覺得特別有表現力,而且我遇到了這個問題。 在某些情況下,根據 DOM 加載的順序,一個 iframe 將有正確的數據可用,而另一個則根本沒有。

我現在的想法(並接受建議)是在父頁面中加載 AJAX 一次,將我需要的數據存儲為本地存儲變量,然后從每個 iframe 中調用這些數據。 想法是它加載一次(在調用 iframe 之前),以便每次都在那里並定義數據。

作為概念的粗略證明,我有這個;

父頁面

$.ajax({
  url: 'https://www.urlofsite.com/mylookupfile.php',
  type: 'POST',
  dataType : 'text',
  data: {Finder: finderID}, 
  success: finderAccess,
  error: finderDecline
});

function finderAccess(data) {
  console.log("sucessful send:");   
  
  // Parsing the returned data from the DB into a JSON object
  var useableData = $.parseJSON(data);
  console.log(useableData);

 // Set the session variables that will be used by each form 
  localStorage.setItem('fName', useableData.fname);
  const sessfName = localStorage.getItem('fName');  

  localStorage.setItem('lName', useableData.lname);
  const sesslName = localStorage.getItem('lName'); 

 }

 //error function and some other non-related scripts follow
  

所以現在我已經設置了我的 session 變量,它可以在父頁面中工作。 如果我打電話給類似的東西

$(".class-name-of-a-p").html(sessfName);

帶有 class 的段落正確顯示存儲在變量中的值。

現在轉到 iframe...

Iframe

  $("#person_first_name").val(sessfName);
  $("#person_last_name").val(sesslName);

我對 HTML Local Storage 創建本地存儲變量的方法的理解是只要域相同就可以使用。 這里就是這種情況,但是,在 iframe 中,控制台告訴我變量不存在並引發錯誤。

將 Ajax 請求存儲在window object 中(在您的頂級框架中):

window.lookup = $.ajax({
  url: 'https://www.urlofsite.com/mylookupfile.php',
  type: 'POST',
  dataType : 'text',
  data: {Finder: finderID}, 
});

現在,在你的每個子框架中,你可以做

window.parent.lookup.done(function (data) {
    // work with data
});

並且所有 iFrame 都會在請求出現后立即收到請求。

這是有效的,因為$.ajax返回 promise。 這個 promise 存儲在window.lookup中。 您可以根據需要向 promise 注冊盡可能多的.done()回調 - 當承諾的結果(在這種情況下為 Ajax 請求)可用時,所有這些回調都會收到通知。 它還緩存數據 - 稍后加載(或稍后創建)的幀將立即收到結果。


如果您想在將數據傳遞給子框架之前進行一些預處理,請在主頂部框架中使用.then()

window.lookup = $.ajax({
  url: 'https://www.urlofsite.com/mylookupfile.php',
  type: 'POST',
  dataType : 'text',
  data: {Finder: finderID}, 
}).then(function (data) {
  var modifiedData = doSomethingWith(data);
  return modifiedData;
});

現在所有子幀都將收到modifiedData

錯誤處理可以在頂部框架中完成(此錯誤處理程序將被調用一次):

window.parent.lookup.done(function (data) {
    // work with data
}).fail();
  url: 'https://www.urlofsite.com/mylookupfile.php',
  type: 'POST',
  dataType : 'text',
  data: {Finder: finderID}, 
}).fail(function (jqXHR, textStatus, errorThrown) {
  finderDecline();
});

或在子框架中(每幀調用一次):

window.parent.lookup.done(function (data) {
  // work with data
}).fail(function (jqXHR, textStatus, errorThrown) {
  // do something appropriate
});

或兩者兼而有之。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM