2017-09-29 58 views
3

我試圖將數據存儲到IndexedDB中,但遇到了問題。當嘗試添加格式正確的JSON數據出現錯誤:IndexedDB - 提供給操作的數據不符合要求

DataError: Data provided to an operation does not meet requirements. 

下面是我的IndexedDB的代碼:

function dbInit(key, value) { 
    // Open (or create) the database 
    var open = indexedDB.open("MyDatabase", 6); 

    // Create the schema 
    open.onupgradeneeded = function() { 
     var db = open.result; 
     var store = db.createObjectStore("MyObjectStore", {keyPath: "id", autoIncrement: true}); 
     var index = store.createIndex("types", "types"); 
    }; 

    open.onsuccess = function() { 
     // Start a new transaction 
     var db = open.result; 
     var tx = db.transaction("MyObjectStore", "readwrite"); 
     var store = tx.objectStore("MyObjectStore"); 
     var index = store.index("types"); 


     // Add some data 
     store.put(value); 


     // Close the db when the transaction is done 
     tx.oncomplete = function() { 
      db.close(); 
     }; 
    } 
} 

通過我注意到一些類似的問題,尋找後,這個問題是存在,如果一個keyPath沒有被指定,但在下面我已經指定keyPath爲「id」和autoIncrement:true,所以這應該作爲keyPath。

下面是我試圖添加的JSON數據 - 通過'值'參數下的函數。 (修改後的數據,因爲它是sensetitive,但這種格式。)

[{ 
    "code": 1, 
    "content": "XXX.html", 
    "scheme": 4, 
    "type": "XXX" 
}, { 
    "code": 2, 
    "content": "XXX.html", 
    "scheme": 6, 
    "type": "XXX" 
}, { 
    "code": 3, 
    "content": "XXX.html", 
    "scheme": 1, 
    "type": "XXX" 
}, { 
    "code": 4, 
    "content": "XXX.html", 
    "scheme": 4, 
    "type": "XXX" 
}] 
+2

我看不出有任何麻煩。 [jsfiddle示例](https://jsfiddle.net/4o2obfe0/1/)。我已經使用了你的函數和[有](https://imgur.com/a/E3QWS)結果截圖(你可以在Chrome DevTools Application選項卡上看到自己)。同時檢查你的JSON,結尾處有'}'而不是']' –

+2

有趣。也許這是一個Firefox問題?我每次都遇到這個錯誤,不幸的是,這是一個Firefox應用程序,不會在Chrome上運行。剛剛注意到JSON末尾的},編輯堆棧溢出的JSON時,這只是一個錯字,並且是在實時代碼中的]。 –

+1

嗯,沒有任何插件的Firefox [給我同樣的結果](https://imgur.com/a/EGmKz)(操作系統:Windows 10)。 –

回答

0

你是在傳遞值作爲一個字符串或解析成一個數組?

如果是字符串,那麼問題是生成的密鑰(c/o autoIncrement: true)無法分配給值(c/o keyPath: "id"),因爲您無法向字符串添加屬性。

簡單的攝製:

indexedDB.open('k').onupgradeneeded = e => { 
    const db = e.target.result; 
    const s = db.createObjectStore('s', {keyPath: 'id', autoIncrement: true}); 
    s.put('string'); 
};