IndexedDB - 搜索特定数据?如何从一行中的另一个值中查找值?

时间:2022-09-25 08:49:36

Below is my example that I have. So far it does the following.

以下是我的例子。到目前为止,它做了以下事情。

  • Enter in 3 values to a row
  • 在一行中输入3个值

  • Retrieve all the values from all rows on load
  • 从load中的所有行检索所有值

  • Place all the values from each row and print them to screen that was retrieved from the above step.
  • 放置每行的所有值,并将它们打印到从上面步骤检索到的屏幕。

The part that I need help with is trying to find all the values of one row based on a value that exists in that row.

我需要帮助的部分是尝试根据该行中存在的值查找一行的所有值。

If a row contains the values name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ I would like to get all the data of that row when some one searches for ‘Andrew’

如果一行包含值名称:'Andrew',电话:'555-55555',地址:'123那边'我想获得该行的所有数据,当有人搜索'Andrew'时

So far if you look at the function ‘searchItems’ you will see that I am trying to find data based on the value of the search input. The problem I am having is all I can get it to do is alert an “undefined” response. How can I write the function to have it find things like described above

到目前为止,如果您查看函数'searchItems',您将看到我正在尝试根据搜索输入的值查找数据。我遇到的问题是我可以做的就是警告“未定义”的响应。如何编写函数让它找到如上所述的内容

Also one step further. How can i edit the data that is in the row that was found based on the search input? (I have not written that function yet)

还有一步。如何编辑基于搜索输入找到的行中的数据? (我还没写过那个功能)

html

<!--jquery-2.1.4.js-->

<body>
  <input type="text" id="dataGoesHere" /> 
   <input type="text" id="moredataGoesHere" />
   <input type="text" id="mostdataGoesHere" />
    <button id="clickme">Save</button>
    <div id="saved"></div>
	
	<br><br>
	
	 <input type="text" id="searchString" /> 
    <button id="search">search</button>

</body>

js

$(document).ready(function() {
	
	myDb = function () {
		var name = "test",
		version = "1",
		db,
		testStoreName = "exampleStore",
		testIndexName = "testIndexName",
		addToTestIndex = false,

		init = function () {
			var deferred = $.Deferred(),
			openRequest = indexedDB.open(name, version);

			openRequest.onupgradeneeded = dbUpgrade;
			openRequest.onsuccess = dbOpen;
			openRequest.onerror = dbError;

			return deferred.promise();

			function dbUpgrade(evt) {
				//here our db is at evt.target.result here we can adjust stores and indexes
				var thisDb = evt.target.result, //the current db we are working with
				newStore = thisDb.createObjectStore(testStoreName, {keyPath: "id", autoIncrement: true});
				//Using indexes, you can target specific keys, this can be an array!
				newStore.createIndex("testIndexKey", "testIndexKey", {unique : false});
				console.log("Doing an upgrade");
			}

			function dbOpen(evt) {
				console.log("DB successfully opened");
				db = evt.target.result;
				deferred.resolve();

				getAllItems (function (items) {
					var len = items.length;
					for (var i = 0; i < len; i += 1) {
						console.log(items[i]);
						$('#saved').append('<p>'+items[i].item + ' ' + items[i].george + ' ' + items[i].column3 + ' ' + items[i].id + '</p>');
					}
				});
			}

			function dbError(error) {
				console.log("DB Error");
				console.log(error);
				deferred.reject(error);
			}
		},

		add = function(item, bob, villa) {
			var itemToAdd = {"item" : item, "george" : bob, "column3" : villa},
			objStore,
			request,
			deferred = $.Deferred();
			if (!addToTestIndex) {
				//here we will add half the entries to the index
				//See http://*.com/questions/16501459/javascript-searching-indexeddb-using-multiple-indexes for a better example
				addToTestIndex = !addToTestIndex;
				itemToAdd.testIndexKey = "This is a test";
			}

			//first get the object store with the desired access
			objStore = db.transaction([testStoreName], "readwrite").objectStore(testStoreName);
			//next create the request to add it
			request = objStore.add(itemToAdd);
			request.onsuccess = function (evt) {
				deferred.resolve(evt.target.result);
			};

			request.onerror = function (evt) {
				deferred.reject(evt);
			};

			return deferred.promise();
		},

		get = function (index) {
			//Since our store uses an int as a primary key, that is what we are getting
			//The cool part is when you start using indexes...
			var deferred = $.Deferred(),
			store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
			request = store.get(parseInt(index));

			request.onsuccess = function (evt) {
				console.log(evt);
				deferred.resolve(evt.target.result);
			};

			request.onerror = function (evt) {
				deferred.reject("DBError: could not get " + index + " from " + testStoreName);
			};

			return deferred.promise();
		},
			
		getAllItems = function(callback) {
			var trans = db.transaction(testStoreName, IDBTransaction.READ_ONLY);
			var store = trans.objectStore(testStoreName);
			var items = [];

			trans.oncomplete = function(evt) {  
				callback(items);
			};

			var cursorRequest = store.openCursor();

			cursorRequest.onerror = function(error) {
				console.log(error);
			};

			cursorRequest.onsuccess = function(evt) {                    
				var cursor = evt.target.result;
				if (cursor) {
					items.push(cursor.value);
					cursor.continue();
				}
			};
		},

		searchItems = function(searchString) {
			var deferred = $.Deferred(),
			store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
			request = store.get(searchString);
			request.onerror = function(event) {
				// Handle errors!
				alert("error");
			};
			
			request.onsuccess = function(event) {
				alert('start seach')
				// Do something with the request.result!)
				alert(event.target.result);
				alert('end search')
			};
		};
		 
		return {
			init: init,
			get: get,
			add: add,
			getAllItems: getAllItems,
			searchItems: searchItems
		};
	}

  var db = new myDb();
  db.init().then(function () {
	$("#clickme").click(function(evt) {
		//add, then we will get the added item from the db
		console.log("Adding new item to db");
		
		db.add($('#dataGoesHere').val(), $('#moredataGoesHere').val(), $('#mostdataGoesHere').val())
		
		.then(function (res) {
			return db.get(res);
		})
		
		.then(function (res) {
			$('#saved').append('<p>'+res.item+' '+res.george+' '+res.column3+'</p>');
		});
	});
	
	$("#search").click(function(evt) {
		// search for a specific row
		console.log("searching");

		db.searchItems($('#searchString').val());
	});
	
	
  })


});

1 个解决方案

#1


First thing (and could be the probable cause): Are you having an index on the key you are trying to search? In you case, for data as name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ if you trying to search for "Andrew", then you should be having an index created on "name". If it is not there then you will not be able to make a search and that's what probably could be happening.

第一件事(可能是可能的原因):你有关于你想要搜索的密钥的索引吗?在你的情况下,对于数据名称:'安德鲁',电话:'555-55555',地址:'123那边'如果你试图搜索“安德鲁”,那么你应该在“名字”上创建一个索引。如果它不存在那么你将无法进行搜索,这可能是可能发生的事情。

Next: In the data store there could be more than one rows with name as Andrew, so you can have a cursor open using the index and then loop through all value and get the desired one. Something like (I am just throwing you an idea through this code snippet):

下一步:在数据存储中可能有多个名称为Andrew的行,因此您可以使用索引打开游标,然后遍历所有值并获取所需的值。类似的东西(我只是通过这个代码片段给你一个想法):

var objectStoreHandler = transaction.objectStore(selectDataObj.tblName);
var indexHandler = objectStoreHandler.index(selectDataObj.whereColObj.whereColNameArr[0]);
var cursorHandler = indexHandler.openCursor(keyRange);
cursorHandler.onsuccess = function (event) {
    var cursor = event.target.result;
    if (cursor) {
        console.log("!!!!!");
        if (cursor.value != null && cursor.value != undefined) {
            resultArr.push(cursor.value);
        }
        cursor["continue"]();
    } else {
        console.log("################### " + resultArr);
        return successCallBack(resultArr);
    }
    return;
};

#1


First thing (and could be the probable cause): Are you having an index on the key you are trying to search? In you case, for data as name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ if you trying to search for "Andrew", then you should be having an index created on "name". If it is not there then you will not be able to make a search and that's what probably could be happening.

第一件事(可能是可能的原因):你有关于你想要搜索的密钥的索引吗?在你的情况下,对于数据名称:'安德鲁',电话:'555-55555',地址:'123那边'如果你试图搜索“安德鲁”,那么你应该在“名字”上创建一个索引。如果它不存在那么你将无法进行搜索,这可能是可能发生的事情。

Next: In the data store there could be more than one rows with name as Andrew, so you can have a cursor open using the index and then loop through all value and get the desired one. Something like (I am just throwing you an idea through this code snippet):

下一步:在数据存储中可能有多个名称为Andrew的行,因此您可以使用索引打开游标,然后遍历所有值并获取所需的值。类似的东西(我只是通过这个代码片段给你一个想法):

var objectStoreHandler = transaction.objectStore(selectDataObj.tblName);
var indexHandler = objectStoreHandler.index(selectDataObj.whereColObj.whereColNameArr[0]);
var cursorHandler = indexHandler.openCursor(keyRange);
cursorHandler.onsuccess = function (event) {
    var cursor = event.target.result;
    if (cursor) {
        console.log("!!!!!");
        if (cursor.value != null && cursor.value != undefined) {
            resultArr.push(cursor.value);
        }
        cursor["continue"]();
    } else {
        console.log("################### " + resultArr);
        return successCallBack(resultArr);
    }
    return;
};