javascript google.script.run.withSuccessHandler()返回空值

hi3rlvi2  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(128)

我需要检索这个函数发送的数据,并将其显示在一个HTML表中

//Function to get All Patients List...
const getAllPatientsList = () => {
  try {
    const responseProcessorSheet = dataColSpreadSheet.getSheetByName('ReponsesProcessor');

    if (responseProcessorSheet.getRange('A2').isBlank()) return;

    const iDIndex = getColumnIndexFromName(responseProcessorSheet, 'ID');
    const isCompleteIndex = getColumnIndexFromName(responseProcessorSheet, 'IsComplete');
    const isApprovedIndex = getColumnIndexFromName(responseProcessorSheet, 'isApproved');
    const isRejectedIndex = getColumnIndexFromName(responseProcessorSheet, 'isRejected');
    const rejReasonsIndex = getColumnIndexFromName(responseProcessorSheet, 'RejectionReasons');
    const isSheduledIndex = getColumnIndexFromName(responseProcessorSheet, 'IsScheduled');
    const toBeReScheduledIndex = getColumnIndexFromName(responseProcessorSheet, 'ToBeReScheduled');
    const dentalCodesIndex = getColumnIndexFromName(responseProcessorSheet, 'DentalCodes');
    const surgeryDateIndex = getColumnIndexFromName(responseProcessorSheet, 'Surgery Date');
    const referringOfficeNameIndex = getColumnIndexFromName(responseProcessorSheet, 'Referring Office Name');
    const patientFirstNameIndex = getColumnIndexFromName(responseProcessorSheet, 'Patient First Name');
    const patientLastNameIndex = getColumnIndexFromName(responseProcessorSheet, 'Patient Last Name');
    const genderAtBirthIndex = getColumnIndexFromName(responseProcessorSheet, 'Gender at Birth');
    const patientDateOfBirthIndex = getColumnIndexFromName(responseProcessorSheet, `Patient's Date of Birth`);
    const wisdomTeethNumbersIndex = getColumnIndexFromName(responseProcessorSheet, `Wisdom Teeth Numbers to be Extracted`);
    const otherTeethNumbersIndex = getColumnIndexFromName(responseProcessorSheet, 'Other Teeth Numbers to be Extracted');
    const responsiblePartyFirstNameIndex = getColumnIndexFromName(responseProcessorSheet, `Responsible Party's First Name`);
    const responsiblePartyLastNameIndex = getColumnIndexFromName(responseProcessorSheet, `Responsible Party's Last Name `);
    const responsiblePartyPhoneNumberIndex = getColumnIndexFromName(responseProcessorSheet, `Responsible Party's Phone Number`);
    const responsiblePartyEmailIndex = getColumnIndexFromName(responseProcessorSheet, `Responsible Party's Email`);
    const patientXRayIndex = getColumnIndexFromName(responseProcessorSheet, `Patient  X-Ray `);
    const allPatientData = [];

    const sheetValues = responseProcessorSheet.getRange(2, 1, responseProcessorSheet.getLastRow() - 1, responseProcessorSheet.getLastColumn()).getValues();

    for (let data of sheetValues) {
      if (data[iDIndex - 1] === '' || data[iDIndex - 1] === null) continue;

      let temp = {};
      temp['iD'] = data[iDIndex - 1];
      temp['isComplete'] = data[isCompleteIndex - 1];
      temp['isApproved'] = data[isApprovedIndex - 1];
      temp['isRejected'] = data[isRejectedIndex - 1];
      temp['rejReasons'] = data[rejReasonsIndex - 1];
      temp['isSheduled'] = data[isSheduledIndex - 1];
      temp['toBeReScheduled'] = data[toBeReScheduledIndex - 1];
      temp['dentalCodes'] = data[dentalCodesIndex - 1];
      temp['surgeryDate'] = data[surgeryDateIndex - 1];
      temp['referringOfficeName'] = data[referringOfficeNameIndex - 1];
      temp['patientFirstName'] = data[patientFirstNameIndex - 1];
      temp['patientLastName'] = data[patientLastNameIndex - 1];
      temp['genderAtBirth'] = data[genderAtBirthIndex - 1];
      temp['patientDateOfBirth'] = data[patientDateOfBirthIndex - 1];
      temp['wisdomTeethNumbers'] = data[wisdomTeethNumbersIndex - 1];
      temp['otherTeethNumbers'] = data[otherTeethNumbersIndex - 1];
      temp['responsiblePartyFirstName'] = data[responsiblePartyFirstNameIndex - 1];
      temp['responsiblePartyLastName'] = data[responsiblePartyLastNameIndex - 1];
      temp['responsiblePartyPhoneNumber'] = data[responsiblePartyPhoneNumberIndex - 1];
      temp['responsiblePartyEmail'] = data[responsiblePartyEmailIndex - 1];
      temp['patientXRay'] = data[patientXRayIndex - 1];

      allPatientData.push(temp);
    };
    console.log("Patients récupérés :", allPatientData);
    return allPatientData;
  } catch (error) {
    Logger.log(`getAllPatientsListError: ${error.message}`);
    return `getAllPatientsListError: ${error.message}`;
  };
 
};

服务器端数据以这种格式返回。我从服务器端日志里找到的。

[ { iD: 1683945240392,
    isComplete: '',
    isApproved: '',
    isRejected: '',
    rejReasons: '',
    isSheduled: '',
    toBeReScheduled: '',
    dentalCodes: '',
    surgeryDate: '',
    referringOfficeName: 'Office 1',
    patientFirstName: 'laura',
    patientLastName: 'WAx',
    genderAtBirth: 'Female',
    patientDateOfBirth: Tue Jun 13 1995 00:00:00 GMT+0200 (Central European Summer Time),
    wisdomTeethNumbers: 16,
    otherTeethNumbers: '12,5,6',
    responsiblePartyFirstName: 'Tom',
    responsiblePartyLastName: 'Jerry',
    responsiblePartyPhoneNumber: '+22996764654',
    responsiblePartyEmail: 'blockchaindevxinxi@gmail.com',
    patientXRay: 'https://drive.google.com/open?id=1NZKUpQ1uevK2QI26n-E4VWSvfju7aPvW' },
  { iD: 1683945737559,
    isComplete: '',
    isApproved: '',
    isRejected: '',
    rejReasons: '',
    isSheduled: '',
    toBeReScheduled: '',
    dentalCodes: '',
    surgeryDate: '',
    referringOfficeName: 'Office2',
    patientFirstName: 'ken',
    patientLastName: 'Smith',
    genderAtBirth: 'Male',
    patientDateOfBirth: Thu Aug 08 1991 00:00:00 GMT+0200 (Central European Summer Time),
    wisdomTeethNumbers: 'All 4 Wisdom Teeth (1, 16, 17, 32)',
    otherTeethNumbers: '5,6',
    responsiblePartyFirstName: 'Lebron',
    responsiblePartyLastName: 'Jordan',
    responsiblePartyPhoneNumber: 22996764654,
    responsiblePartyEmail: 'blockchaindevxinxi@gmail.com',
    patientXRay: 'https://drive.google.com/open?id=1I3Wsz6XA69f8h9JlAy3gZ8RcnfdAyHSO' } ]

我在navigatur端编写了这个函数,以便能够检索数据

document.addEventListener('DOMContentLoaded', function() {
  init();
});

function init() {
  console.log("Avant appel à google.script.run");
  google.script.run.withSuccessHandler(displayPatients).getAllPatientsList();
}

function displayPatients(patients) {
  var tableBody = document.querySelector('#data_table_all tbody');
  tableBody.innerHTML = ''; // Efface les données précédentes du tableau (s'il y en a)
  console.log(patients);
  if (patients && patients.length) { // Vérifie que la variable patients est définie et contient des éléments
    console.log("Longueur du tableau patients :", patients.length);
    patients.forEach(function(patient) {
      console.log("Patient en cours de traitement :", patient);
      let row = document.createElement('tr');

      let nameCell = document.createElement('td');
      nameCell.textContent = patient.patientFirstName + ' ' + patient.patientLastName;
      row.appendChild(nameCell);
      console.log("Prénom du patient :", patient.patientFirstName);
      var ageCell = document.createElement('td');
      var birthDate = new Date(patient.patientDateOfBirth);
      var today = new Date();
      var age = today.getFullYear() - birthDate.getFullYear();
      ageCell.textContent = age;
      row.appendChild(ageCell);

      var addressCell = document.createElement('td');
      addressCell.textContent = patient.referringOfficeName;
      row.appendChild(addressCell);

      // ... Ajoutez d'autres cellules de données selon vos besoins

      tableBody.appendChild(row);
    });
  } else {
    // Si patients est null ou ne contient pas d'éléments, affichez un message d'erreur dans le tableau
    var errorRow = document.createElement('tr');
    var errorCell = document.createElement('td');
    errorCell.colSpan = 3; // Étend la cellule sur trois colonnes pour occuper tout l'espace disponible
    errorCell.textContent = 'Aucun patient trouvé';
    errorRow.appendChild(errorCell);
    tableBody.appendChild(errorRow);
  }
}

getAllPatientsList()函数返回了一个没有被displayPatients()函数的参数接收到的对象,我得到了一个null,而不是你看到我的浏览器控制台,你能帮助我吗

uubf1zoe

uubf1zoe1#

你做错了什么?

在代码的上下文中,您遇到了一个问题,即getAllPatientsList()函数返回的对象未被displayPatients()函数的参数接收。问题是你试图返回一个不可接受的类型的数据到客户端。通过google.script.run调用的函数对它们可以返回的内容有限制(例如,您应该避免Date示例)。

限制类型

目前,您不能返回(查看文档以了解限制的详细说明):

  1. Date示例;
    1.任何Function;
  2. DOM元素(尽管允许<form>);

那我们能做什么?

要修复此问题,可以使用一种解决方法,分别使用JSON.stringify()和JSON.parse()序列化然后反序列化对象。通过这样做,您强制执行了一个常规的JavaScript序列化来避免这个问题。
你只需要做三个步骤
1.将return allPatientData;更改为return JSON.stringify(allPatientData);
1.将参数function displayPatients(patients)更改为function displayPatients(data)
1.在函数显示的顶部添加一行患者var patients = JSON.parse(data);
下面是修复该问题的代码片段:

function getAllPatientsList() {
  // ...
  return JSON.stringify(allPatientData);
}

function displayPatients(data) {
  var patients = JSON.parse(data);
  // ...
}

相关问题