如何写一个在WEB网页中调用以太坊智能合约的DAPP

在【使用web3调用智能合约的简单例子】中,使用的是Nodejs来调用智能合约,Nodejs适合做服务器端的应用。如何在WEB网页中调用智能合约,其实方法类似,同样是使用web3.js库。网页版例子的运行效果如下图所示,更加的直观。

网页版的例子,同样的为了简单起见,仍旧直接使用Remix自带的Storage.sol合约例子,就是简单的存储和获取一个整数数值。前两个步骤 【1.编写智能合约】 和 【2.部署智能合约】 与【使用web3调用智能合约的简单例子】的前两个步骤完全一样,这里主要讲述一下后面的两个步骤 【3. 安装一个简易版的WEB服务器】 和 【4. 在网页中调用智能合约】。

3. 安装一个简易版的WEB服务器

使用 lite-server(https://www.npmjs.com/package/lite-server) 一个轻量级的Nodejs实现的WEB服务器,作为开发使用很方便,安装方式:

npm install lite-server --save-dev

配置:在package.json文件中增加

“scripts”: {“dev”: “lite-server”}

启动

npm run dev

启动后就会在浏览器中自动打开当前目录下的 index.html 页面,我们就在这个页面中使用 javascript 实现具体的逻辑。

4. 在网页中调用智能合约

开始使用jQuery开发index.html网页,主要的代码是:

if (window.ethereum) { //连接到Metamask web3 = new Web3(ethereum); } else { ///直接连接到Ganache web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545")); } //读取合约的ABI信息 var data = $.ajax({ url: "./Storage.json", async: false }).responseText; //创建合约对象,使用的合约地址是我们刚创建的合约地址 var contract = new web3.eth.Contract(JSON.parse(data), '0xc8b522331e8A2369e87Cb4be6bE7C74Be86f1AAB'); $("#setValue").click(function () { try { ethereum.enable(); contract.methods.store($("#txtValue").val()).send({ from: '0x51BF497D8B47C5754220be9256F0Cb9E2Cd688B8' }); $("#msg").text("设置值成功!"); } catch (err) { $("#msg").text("设置值失败:" + err.message); } }); $("#getValue").click(function () { contract.methods.retreive().call().then(function (result) { $("#spanValue").val(result); $("#msg").text("获取值成功!"); }); });

需要说明的是:

  1. 在网页中使用MetaMask连Ganache时,需要使用注入的ethereum作为提供者。上段代码中的第1到4行。
  2. 为了在网页中使用MataMask的用户账号send事务,必须要调用ethereum.enable先。上段代码中的第17到18行。
  3. 代码中第10行Storage.json文件中的内容是Storage合约的ABI文件,点击在Remix编译面板底部的ABI按钮可以复制出来然后粘贴到Storage.json文件中。

完整的网页代码如下,为了让页面长得好看些,使用了Bootstrap,如果不关注可以无视。重点关注上一段代码。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>最简单的DAPP</title> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script src="./node_modules/web3/dist/web3.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> </head> <body> <div class="container"> <div class="jumbotron"> <h2>我的第一个 DAPP</h2> <p>使用 web3.js 调用以太坊智能合约 smart contract 的简单例子</p> </div> <div class="jumbotron"> <form class="bs-example bs-example-form" role="form"> <div class="row"> <div class="col-lg-12"> <div class="input-group input-group-lg"> <span class="input-group-btn"> <button id="setValue" class="btn btn-default btn btn-danger" type="button"> 设置值: </button> </span> <input type="text" class="form-control" id="txtValue"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </div> </form> </div> <div class="jumbotron"> <form class="bs-example bs-example-form" role="form"> <div class="row"> <div class="col-lg-12"> <div class="input-group input-group-lg"> <span class="input-group-btn"> <button class="btn btn-default btn-success" type="button" id="getValue"> 获取值: </button> </span> <input type="text" id="spanValue" class="form-control"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </div> </form> </div> <div class="row"> <div class="col-lg-12 "> <div id="msg" class="alert alert-danger"></div> </div> </div> <script> if (window.ethereum) { //连接到Metamask web3 = new Web3(ethereum); } else { ///直接连接到Ganache web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545")); } //读取合约的ABI信息 var data = $.ajax({ url: "./Storage.json", async: false }).responseText; //创建合约对象,使用的合约地址是我们刚创建的合约地址 var contract = new web3.eth.Contract(JSON.parse(data), '0xc8b522331e8A2369e87Cb4be6bE7C74Be86f1AAB'); $("#setValue").click(function () { try { ethereum.enable(); contract.methods.store($("#txtValue").val()).send({ from: '0x51BF497D8B47C5754220be9256F0Cb9E2Cd688B8' }); $("#msg").text("设置值成功!"); } catch (err) { $("#msg").text("设置值失败:" + err.message); } }); $("#getValue").click(function () { contract.methods.retreive().call().then(function (result) { $("#spanValue").val(result); $("#msg").text("获取值成功!"); }); }); </script> </body> </html>

在浏览器中打开就能看到本文第一张图的页面了,分别点击【设置值】和【获取值】按钮就能自由的和Storage合约交互了。OMG,惊不惊喜,意不意外,哈哈哈。

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

微信号已复制,请打开微信添加咨询详情!
-->