将信息从 Drupal 7 中的模块文件传递给 JS 文件

Passing information to JS File from Module File in Drupal 7

本文关键字:文件 JS 模块 信息 Drupal      更新时间:2023-09-26

在我的一个网页中,我多次打印一个按钮,并且都有不同的logId。我希望当用户单击时,图片中将有 JQuery,并且不应该有服务器端回发。由于每个按钮都关联了唯一的日志 ID,因此我将信息从 * 传递到 JS 文件。单击按钮时的模块如下:-

*.模块文件 -- PHP 文件

$thm_button .= '<input type="button" class="clsPrevious" id="btnPrev_'.$user->uid.'_'.$logid;>';

*.js 文件

$('.clsPrevious', context).click(function (event) {
   var previousLog=this.id.split('_');
   //Retrieve log Id and Process the log id using AJAX call
}

这在这里工作正常,但我觉得存在安全问题,因为每个人都可以在 HTML 源代码中查看按钮的日志 ID。

Drupal/PHP/HTML中是否有任何方法可以将敏感信息传递给JS,而不会显示在HTML查看器中。

您可以使用"Drupal.settings"将值从PHP传递到Javascript。

在此处阅读更多相关信息。

您可以创建一个如下所示的输入按钮。

$thm_button .= '<input type="button" class="clsPrevious" data-myModule=" . $key . ">;

其中$key是随机/串行变量,但每个日志 ID 都是唯一的。

创建一个键值对的映射数组并使用 drupal_add_js() 传递给 javasript

<?php
  drupal_add_js(array('myModule' => array('_YOUR_CUSTOM_KEY_1_' => '_LOG_ID_1_')), 'setting');
?>

现在将您的点击功能修改为,

$('.clsPrevious', context).click(function (event) {
  var key = $(this).attr("data-myModule");
  // Now a this point you have the lookup table in Drupal.settings.myModule
  // use the "key" variable to find the LOG ID
}