【问题标题】:Access function in external js file from button in webapp从 webapp 中的按钮访问外部 js 文件中的函数
【发布时间】:2020-03-16 18:36:11
【问题描述】:

我的 /js 文件夹中有一个文件 dmreboot_service.js。当我使用 node /js/dmreboot_service.js 运行此文件时,它成功地调用了 Azure 中的直接方法。

我需要能够在我的网络应用程序中单击按钮时执行此功能或文件。

我尝试使用以下方法将脚本加载到我的 html 头部:

<script src="js/dmreboot_service.js"></script>

我在外部文件中添加了警报。 如果我将此警报放在文件的顶部它可以工作,但在 底部失败,所以文件的内容没有加载。

dmreboot_service.js 的内容是:

'use strict';

var Registry = require('azure-iothub').Registry;
var Client = require('azure-iothub').Client;


var connectionString ="HostName=XxxxxxxX.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=XxxxxxxxxxxxxxxxxxxxxxxxxxxxxxX=";
var registry = Registry.fromConnectionString(connectionString);
var client = Client.fromConnectionString(connectionString);
var deviceToReboot = 'Runner';

var startRebootDevice = function (twin) {

  var methodName = "reboot";

  var methodParams = {
      methodName: methodName,
      payload: null,
      timeoutInSeconds: 30
  };

  client.invokeDeviceMethod(deviceToReboot, methodParams, function(err, result) {
      if (err) {
          console.error("Direct method error: "+err.message);
      } else {
          console.log("Successfully invoked the device to reboot.");  
      }
  });
};

var queryTwinLastReboot = function() {

  registry.getTwin(deviceToReboot, function(err, twin){

      if (twin.properties.reported.iothubDM != null)
      {
          if (err) {
              console.error('Could not query twins: ' + err.varructor.name + ': ' + err.message);
          } else {
              var lastRebootTime = twin.properties.reported.iothubDM.reboot.lastReboot;
              console.log('Last reboot time: ' + JSON.stringify(lastRebootTime, null, 2));
          }
      } else 
          console.log('Waiting for device to report last reboot time.');
  });
};

startRebootDevice();
setInterval(queryTwinLastReboot, 2000);

alert('dmreboot included!');

我也尝试在我的 html 头部创建一个函数,其中包含 dmreboot_service.js 的全部内容,但是尽管成功调用了该函数,但代码并没有执行。

这是我需要开始工作的项目的最后一部分。我对此很陌生,这让我发疯了!非常感谢任何建议。

【问题讨论】:

  • 更新:我已将问题追溯到使用 Require 的两行代码。浏览器不支持 Require。将研究显然启用此功能的 browserify 或 requirejs。

标签: javascript jquery html node.js azure-iot-hub-device-management


【解决方案1】:

我通常使用 javascript 处理 HTML 中的点击;

const doSomething = document.querySelector('.whateverclassnameyouchoose').addEventListener('click',onClick);

function onClick(e){
what ever you want the function to do
}

希望对你有帮助:)

【讨论】:

  • 您好,非常感谢您的回复,但我想您可能误解了我的问题。我只有通过单击按钮运行此特定功能时遇到问题 这是因为当我使用 时,文件中的代码无法包含在页眉中。如果我把它放在我的 html 中的一个函数中,该代码也无法执行,即使该函数在按钮单击时被成功调用。非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2014-09-05
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多