使用 API 构建二维码生成器

Using an API to build a QR Code Generator

我一直在研究 QR 码生成器,它使用 this API. For some reason, I'm not able to figure out what's wrong with it. Click here 在 JSFiddle 中查看它。

HTML:

<form>
    <input type="text" id="textInput" placeholder="Enter text here">
    <button type="submit" id="submitButton">Submit</button>
</form>
<!-- This image should display the QR Code. -->
<img id="resultImage" src="" alt="">

JavaScript:

var input = document.getElementById('textInput');
var button = document.getElementById('submitButton');
var image = document.getElementById('resultImage');
button.onclick = function() {
    var resultValue = "http://api.qrserver.com/v1/create-qr-code/?data=" + input.value;
    image.setAttribute("src", resultValue);
}

您需要在 onclick 处理程序的末尾添加 return false;,否则点击按钮会导致页面在二维码有时间呈现之前刷新(因为按钮是类型submit)

button.onclick = function() {
    var resultValue = "http://api.qrserver.com/v1/create-qr-code/?data=" + input.value;
    image.setAttribute("src", resultValue);
    return false;
 }