是否可以在 JS 中创建动态字符串?

Is it possible to create dynamic string in JS?

我正在尝试创建一个使用外部 API 生成二维码的简单 html 程序。基本上,JS 为现场提供的数据创建 QR。例如: 为 QR 提供的数据是:

{"accountNumber":"12345678","accountName":"John Doe","bankCode":"ABCBANK"}

let qrcode = select("img");
let aname = document.getElementById('uname');
let accno = document.getElementById('acnum');
let generateBtn = select("button");
let downloadBtn = select("a");

generateBtn.addEventListener("click", generateQR);

function generateQR() {
  let size = "1000x1000";
  let acqr = "{"accountNumber":"{accno}","accountName":"{aname}","bankCode":"BNK"}"; // for creating string:
  let data = acqr.value; // to create value of above:
  let baseURL = "http://api.qrserver.com/v1/create-qr-code/";

  let url = `${baseURL}?data=${data}&size=${size}`; 

  qrcode.src = url;
  downloadBtn.href = url;
  qrfinal.value = "";
}

function select(el) {
  return document.querySelector(el);
}
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Arial;
}
html,
body {
  width: 100%;
  height: 100%;
}
body {
  display: grid;
  justify-content: center;
  align-items: center;
}

.qrbox {
  display: grid;
  grid-template-columns: 1fr auto;
  grid-row-gap: 10px;
  overflow: hidden;
}

img {
  height: 300px;
  width: 300px;
  padding: 1rem;
  border: 2px solid #bada55;
  border-radius: 0.5rem;
  grid-column: 1 / -1;
}

textarea {
  outline: none;
  height: 50px;
  padding: 1rem;
  border: 2px solid #bada55;
  border-radius: 0.5rem;
  grid-column: 1 / -1;
  resize: none;
  
}


button {
  font-size: 1rem;
  color: #000000;
  text-decoration: none;
  border: none;
  outline: none;
  background-color: #bada55;
  padding: 0.5rem 1rem;
  border-radius: 2rem;
  transition: background-color 0.2s;
}
button:hover {
  background-color: #a4be4b;
}
<div class="qrbox">
    <img src="https://github.com/hirokbanik/qrcode/blob/master/default.png?raw=true" alt="qr-code" />
    Full Name
    <textarea id="uname" name="uname" rows="1" cols="50"></textarea>
    Account Number
    <textarea id="acnum" name="acnum" rows="1" cols="50"></textarea>
    <button>Generate QR</button>
</div>

但是,我无法创建动态字符串, 有什么选择吗? 代码笔: https://codepen.io/nepallic/pen/GRWgbNb

您没有具体说明问题,但我认为您在准备数据以将其传递给 url 时遇到了问题。 您可以使用字符串模板更正您的 acqr 声明,类似于您稍后在代码中使用它们的方式:

 let acqr = `{"accountNumber":"${accno}","accountName":"${aname}","bankCode":"BNK"}`;

但我建议使用 JSON.stringify

const acqr = {
    accountName: accno,
    accountNumber: aname,
    bankCode: 'BNK'
};

const data = JSON.stringify(acqr);

您还应该 encode 图书馆文档中所述的数据。

更新

正如您在下面评论的那样,我对您的代码进行了更深入的研究,发现了更多问题。

您得到的是 HTML 元素,而不是它们的值:

let aname = document.getElementById('uname');
let accno = document.getElementById('acnum');

因此要构造您需要获得 .value 这些控件的对象,例如:

const acqr = {
    accountNumber: accno.value,
    accountName: aname.value,
    bankCode: 'BNK'
};

接下来您通过 stringify 对象和 encode 将数据准备为 url 友好字符串,以安全地传入 url.

let data = JSON.stringify(acqr);
data = encodeURIComponent(data);

然后构造url二维码api:

// http(s)://api.qrserver.com/v1/create-qr-code/?data=[URL-encoded-text]&size=[pixels]x[pixels]
const width = height = 150;
const url = `http://api.qrserver.com/v1/create-qr-code/?&data=${data}&size=${width}x${height}`;

最后将创建的 url 设置为您的图像 src,以替换占位符二维码。

qrcode.src = url;

您的代码稍作修改: (你有一些像 qrfinal 这样的变量,它们应该包含 html 元素,但不存在于你的 html 中,所以我在我的代码片段中删除了它们)

        const bankCode = "BNK";
        const qrcode = select("#qrCode");
        const aname = select('#uname');
        const accno = select('#acnum');
        const generateBtn = select("#submit-btn");

        generateBtn.addEventListener("click", generateQR);

        function generateQR() {

            const width = height = 150;
            const acqr = {
                accountNumber: accno.value,
                accountName: aname.value,
                bankCode: bankCode
            };

            // http(s)://api.qrserver.com/v1/create-qr-code/?data=[URL-encoded-text]&size=[pixels]x[pixels]
            let data = JSON.stringify(acqr);
            data = encodeURIComponent(data);
            const url = `http://api.qrserver.com/v1/create-qr-code/?&data=${data}&size=${width}x${height}`;

            qrcode.src = url;
        }

        function select(el) {
            return document.querySelector(el);
        }
        *,
        *::before,
        *::after {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        body {
            display: grid;
            justify-content: center;
            align-items: center;
        }

        .qrbox {
            display: grid;
            grid-template-columns: 1fr auto;
            grid-row-gap: 10px;
            overflow: hidden;
        }

        img {
            height: 300px;
            width: 300px;
            padding: 1rem;
            border: 2px solid #bada55;
            border-radius: 0.5rem;
            grid-column: 1 / -1;
        }

        textarea {
            outline: none;
            height: 50px;
            padding: 1rem;
            border: 2px solid #bada55;
            border-radius: 0.5rem;
            grid-column: 1 / -1;
            resize: none;

        }


        button {
            font-size: 1rem;
            color: #000000;
            text-decoration: none;
            border: none;
            outline: none;
            background-color: #bada55;
            padding: 0.5rem 1rem;
            border-radius: 2rem;
            transition: background-color 0.2s;
        }

        button:hover {
            background-color: #a4be4b;
        }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Generator</title>

</head>

<body>
    <div class="qrbox">
        <img src="https://github.com/hirokbanik/qrcode/blob/master/default.png?raw=true" alt="qr-code" id="qrCode" />
        <label for="uname">Full Name</label>
        <textarea id="uname" name="uname" rows="1" cols="50"></textarea>
        <label for="acnum">Account Number</label>
        <textarea id="acnum" name="acnum" rows="1" cols="50"></textarea>
        <button id="submit-btn">Generate QR</button>
    </div>

</body>

</html>

您可以使用JSON.stringify to convert a JSON object to a JSON string, and use encodeURIComponent对查询参数值进行编码

const size = "1000x1000";
const acqr = {
  "accountNumber": accno,
  "accountName": aname,
  "bankCode": "BNK"
};

const baseURL = "http://api.qrserver.com/v1/create-qr-code/";
const data = encodeURIComponent(JSON.stringify(acqr));

const url = `${baseURL}?data=${data}&size=${size}`; 

qrcode.src = url;