Contract-Invocation
使用 web3js 呼叫“視圖”函式
— 大量編輯 —
Solidity 合約:
pragma solidity ^0.4.24; contract PatientRecords { struct Patient { string ID; string weight; string height; string diseasehistory; string vaccinecard; string name; address registrantAddress; } uint ID; constructor() public { ID = 0; } Patient[] public patients; mapping(string => uint) names; function register(string _id, string _weight, string _height, string _diseasehistory, string _vaccinecard, string _name) public returns (bool, uint){ for (uint i = 0; i < patients.length; i++) { require (stringsEqual(patients[i].ID, _id) == false); } names[_name] = ID; ID++; patients.push(Patient(_id, _weight, _height, _diseasehistory, _vaccinecard, _name, msg.sender)); return (true, ID); } function verifyByName(string _name) public view returns(string, string, string, string, string, string) { uint n; n = names[_name]; return ( patients[n].name, patients[n].ID, patients[n].weight, patients[n].height, patients[n].diseasehistory, patients[n].vaccinecard); } function stringsEqual(string storage _a, string memory _b) internal pure returns(bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (keccak256(a) != keccak256(b)) { return false; } return true; } }
HTML輸入欄&按鈕程式碼:
<input id="name" type="text"> <button id="button2">Search</button>
我需要的:
- 使用者在 HTML 上輸入一個值
- 使用者點擊按鈕
- 值作為參數傳遞給合約的“視圖”函式
- HTML 顯示合約返回的任何內容
那麼,使用上面的程式碼,我怎樣才能達到這 4 點呢?
謝謝你。
如果您理解本教程並遵循所有說明,那就太好了。他們使用 MetaMask,這意味著他們使用 web3js 0.x 版本。
var web3 = window.web3; if (typeof web3 !== 'undefined') { // Use Mist/MetaMask's provider. web3 = new Web3(web3.currentProvider) } else { // Fallback to localhost if no web3 injection. We've configured this to // use the development console's port by default. web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:9545')); } const patientrecordsContract = web3.eth.contract(<ABI>); const instance = patientrecordsContract.at('0xdbdc2f9850e93fbdd894a5916010605f463b66d1') instance.verifyByName("q", (error, data) => { console.log(error, data); });