Uncaught ReferenceError: web3 is not defined at window.onload

Uncaught ReferenceError: web3 is not defined at window.onload

我正在尝试让我的第一个 dapp 工作;我知道我很接近,但请 运行 陷入 web3 的问题。

我正在 Windows 10、运行 一个 testrpc 节点上 PowerShell。我使用 truffle 设置我的文件夹和示例文件,然后编译和迁移。

我认为我没有更改 truffle 构建的 app.js 文件中的任何内容...这是代码:

var accounts;
var account;

function setStatus(message) {
  var status = document.getElementById("status");
  status.innerHTML = message;
};

function refreshBalance() {
  var meta = MetaCoin.deployed();

  meta.getBalance.call(account, {from: account}).then(function(value) {
    var balance_element = document.getElementById("balance");
    balance_element.innerHTML = value.valueOf();
  }).catch(function(e) {
    console.log(e);
    setStatus("Error getting balance; see log.");
  });
};

function calcPremium() {
    var premium = parseInt(document.getElementById("benefit").value)/10000;
    document.getElementById("monthlyPremium").innerHTML = "    Monthly Premium: $"+premium.toFixed(2);

};

function sendCoin() {
  var meta = MetaCoin.deployed();

  var amount = parseInt(document.getElementById("monthlyPremium").value);
  var receiver = document.getElementById("receiver").value;

  setStatus("Initiating transaction... (please wait)");

  meta.sendCoin(receiver, amount, {from: account}).then(function() {
    setStatus("Transaction complete!");
    refreshBalance();
  }).catch(function(e) {
    console.log(e);
    setStatus("Error sending coin; see log.");
  });
};

window.onload = function() {
  web3.eth.getAccounts(function(err, accs) {
    if (err != null) {
      alert("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];

    refreshBalance();
  });
}

我可以使用 MetaMaskChrome 浏览器中打开 html 文件启用插件。但是,由于 web3 错误问题,我似乎无法以任何方式与合同进行交互。确切的消息是这个 post 的主题行。

在此先感谢您的帮助或指导!

你能试试看吗。我认为 onload 给出了问题。

    $(window).load function() {
  web3.eth.getAccounts(function(err,accs) {
    if (err != null) {
      alert("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];

    refreshBalance();
  });
}