【问题标题】:How to save barcodeScanner result to localStorage in cordova plugin barcodeScanner如何在cordova插件barcodeScanner中将barcodeScanner结果保存到localStorage
【发布时间】:2015-06-16 12:04:03
【问题描述】:

我从SAP 获得了一个适用于barcodeScanner wildabeast cordova 插件的教程。 从教程中它有一个 index.html 本身用于调用该函数。然后我将它植入我的应用程序的 index.html 中,代码是这样的:

<div data-role="content" style="text-align: center">
    <h3 style="color: blue">Selamat datang.</h3>
    <button onclick="scan()">Scan QR Code</button> <!-- call function scan() from barcodescanner.js -->
    <a href="#manual" class="ui-btn">Masukkan Kode</a> 
      <div id="scan_results"></div> <!-- unknown -->
</div> <!-- /contain -->

barcodescanner.js 是这样的:

document.addEventListener("deviceready", init, false);
    function init() {
    }

    function scan() {
        log("scanning");
        cordova.plugins.barcodeScanner.scan(scanSuccessCallback, scanErrorCallback);
    }

    function scanSuccessCallback(result) {
        log(JSON.stringify(result));
        /*
        alert("We got a barcode\n" +
        "Result: " + result.text + "\n" +
        "Format: " + result.format + "\n" +
        "Cancelled: " + result.cancelled);
         */
    }

    function scanErrorCallback(error) {
        alert("Scanning failed: " + JSON.stringify(error));
    }

    function encode() {
        log("encoding");
        if (device.platform == "Android") {  //Not supported on iOS
            var stringToEncode = "http://www.sap.com";
            cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, stringToEncode, encodeSuccessCallback, encodeErrorCallback);
        }
        else {
            log("Encoding is not supported on iOS.  See https://github.com/wildabeast/BarcodeScanner/issues/106");  
        }
    }

    function encodeSuccessCallback(result) {
        log(JSON.stringify(result));
    }

    function encodeErrorCallback(error) {
        alert("Encoding failed: " + JSON.stringify(error));
    }

    function log(line) {
        var results = document.getElementById("scan_results");
        results.innerHTML+= "<br>" + line;
    }

我想将扫描结果保存到 LocalStorage 并且结果未显示在应用程序中。有人可以帮我这样做吗? 提前致谢!

【问题讨论】:

    标签: javascript cordova barcode-scanner


    【解决方案1】:

    LocalStorage 实际上只是一个行为与其他对象一样的对象。选择一个属性名称并使用 getter 和 setter,例如:

    localStorage.setItem('item1', '8383838838');
    
    localStorage.getItem('item1');
    

    或者简单地说:

    localStorage.item1 = '8383838838';
    

    请注意,如果您想在其中存储一个对象,您可以,但您必须先对其进行字符串化。

    并不是说这应该是现代浏览器的问题,但是在使用这个 api 之前,请务必先检查 LocalStorage 是否存在。

    【讨论】:

    • 哦,我明白了。从我看到的“item1”是本地存储名称,数字是值。从我的javascript代码中,扫描的结果是'result.text'。这样对吗?它是否已经是字符串类型?对于我的应用,qrcode contect 是字符串类型的代码。
    • 好像如果你尝试将一个数字保存到localstorage,它会自动将它转换为字符串,如果它已经是字符串,你不需要担心。然而,对象并非如此。您必须先对其进行序列化。
    猜你喜欢
    • 2017-07-23
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2023-03-23
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多