为什么在使用indexedDB时未调用onsuccess / onerror回调?

时间:2013-03-20 05:16:55

标签: javascript html5 indexeddb

我正在尝试创建一个登录表单。我在db中有一些用户名(对象)。我创建了一个表单,它提取用户名(主键)并检查它是否在数据库中。但是,在信息通过我的loginCheck()方法之后,页面只刷新并且不会运行成功,也不会运行我设置为调试的失败警报

JS:

//-------------USER DB------------------//
function startDB(){
    //sign in page elements
    logUser = document.getElementById('logUserName');
    logPass = document.getElementById('logPass');
    signin = document.getElementById('signin');
    signin.addEventListener('click',getLogin);

    //register page elements
    mainForm = document.getElementById('mainFormSidebar');
    mainForm.addEventListener('submit',addObject);
    fname = document.getElementById('fName');
    lName = document.getElementById('lName');
    users = document.getElementById('uName');
    pass = document.getElementById('password');
    email = document.getElementById('email');
    dob = document.getElementById('dob');
    phone = document.getElementById('phone');
    bio = document.getElementById('bio');
    terms = document.getElementById('terms');
    school = document.getElementById('school');
    gender = document.getElementsByName('gender');
    save = document.getElementById('save');
    reset = document.getElementById('reset'); 
    reset.addEventListener('click',clearForm);
    databox = document.getElementById('databox');



    //open DB
    var request = indexedDB.open('macroPlay'); 
    //if fails
    request.addEventListener('error', showerror); 
    //if succeeds
    request.addEventListener('success', start); 
    //if !exist, create.
    request.addEventListener('upgradeneeded', createdb); 

    //Create Admin account on launch

}
function showerror(e){
    alert('Error: ' + e.code + ' - ' + e.message);
}
function start(e){
    db = e.target.result;
    chkAdmin();
    showUsers();// Show all values in the object store
}
function createdb(e){
    var datababase = e.target.result;
    var myusers = datababase.createObjectStore('users', {keyPath: 'userName'});
}
function addObject(){
    if(confirm('Are you sure you want to resgister?')){
        var fName = document.getElementById('fName').value;
        var lName = document.getElementById('lName').value;
        var userName = document.getElementById('uName').value;
        var pass = document.getElementById('password').value;
        var email = document.getElementById('email').value;
        var dob = document.getElementById('dob').value;
        var phone = document.getElementById('phone').value;
        var bio = document.getElementById('bio').value;
        var terms = document.getElementById('terms').value;
        var school = document.getElementById('school').value;

        //May need to set a loop to find value of radio
        var gender;
        var radios = document.getElementsByName('gender');

        for (var i = 0, length = radios.length; i < length; i++) {
            if (radios[i].checked) {
                gender=radios[i].value;
            }
        }

        //set up transaction
        var mytransaction = db.transaction(['users'], "readwrite"); 

        //get object store
        var myusers = mytransaction.objectStore('users'); 

        //Add item
        var request = myusers.add(new getUser(userName,fName,lName,pass,email,dob,phone,bio,terms,school,gender));
    }

    // Show all results.
    mytransaction.addEventListener('complete', showUsers);  

    //Reset Form Fields
    resetForm();


}
function getUser(userName, fn, ln, pw, em, dob, tel, bio,tm, scl, gender){
    this.userName = userName;
    this.fn = fn;
    this.ln = ln;
    this.pw = pw;
    this.em = em;
    this.dob = dob;
    this.tel = tel;
    this.bio = bio;
    this.tm = tm;
    this.scl = scl;
    this.gender = gender;
}
function showUsers(){
    //reset box
    databox.innerHTML = ''; 
    //set the transaction 
    var mytransaction = db.transaction(['users']);
    //get object store
    var myusers = mytransaction.objectStore('users');
    //open the cursor and set an order
    var newcursor = myusers.openCursor(null,"prev");
    //show all users on successful load of DB
    newcursor.addEventListener('success',showUserList);
}
function showUserList(e){
    //var result = e.target.result;
    //databox.innerHTML = '<div>' + result.id + ' - ' + result.name + ' - ' + result.date + '</div>';
    var cursor = e.target.result; // Capture multiple return values as a cursor
    // Modify the databox to show the results 
    if (cursor){
   /*
        databox.innerHTML = '<div>' + 
           'Username'+ ' - ' + 
           'First'+ ' - ' + 
           'Last'+ ' - '+ 
           'Pass'+ ' - '+ 
           'Email'+ ' - '+ 
           'DOB'+ ' - '+
           'TEL'+ ' - '+ 
           'BIO'+ ' - '+ 
           'NEWS'+ ' - '+
           'TOS'+ ' - '+
           'SCL'+' - '+
           'Gender </div>';
   */

        databox.innerHTML += '<div>' + 
        cursor.value.userName + ' - ' + 
        cursor.value.fn+ ' - ' + 
        cursor.value.ln+ ' - '+ 
        cursor.value.pw+ ' - '+ 
        cursor.value.em+ ' - '+ 
        cursor.value.dob+ ' - '+
        cursor.value.tel+ ' - '+ 
        cursor.value.bio+ ' - '+ 
        cursor.value.tm+ ' - '+
        cursor.value.scl+' - '+
        cursor.value.gender+ 
        ' <input type="button" onclick="removeobject(\'' + cursor.value.userName + '\')" value="remove"/></div>';
            // Add a remove button as inserted HTML
        cursor.continue(); // Iterates over the cursor
    }
}
function removeobject(keyword){
    // Confirm the deletion
    if(confirm('Are you sure?')){ 
        // Set the transaction
        var mytransaction = db.transaction(['users'], "readwrite"); 
        // Get the object store
        var mystore = mytransaction.objectStore('users'); 
        // Delete the record with the chosen index
        var request = mystore.delete(keyword); 
        // If success, show the updated results
        mytransaction.addEventListener('complete', showUsers); 
    }
}

//reset functions
function clearForm(){
    //Clear form
    if(confirm('Clear all fields?')){
        resetForm();
    }
    showUserList();    
}
function resetForm(){
    //Reset form
    fname = document.getElementById('fName').value='';
    lName = document.getElementById('lName').value='';
    uName = document.getElementById('uName').value='';
    pass = document.getElementById('password').value='';
    email = document.getElementById('email').value='';
    dob = document.getElementById('dob').value='';
    phone = document.getElementById('phone').value='';
    bio = document.getElementById('bio').value='';
    nl = document.getElementById('nl').value='';
    terms = document.getElementById('terms').checked = false;
    school = document.getElementById('school').value='';
    gender = document.getElementsByName('gender').value='';
    showUserList();    
}


//------Create Admin Account-----//
function chkAdmin(){ 
     if(localStorage.getItem('admin')!="added"){             
        alert('Adding administrator Account');
        addAdmin();
    }
}
function addAdmin(){
    //set up transaction
        var mytransaction = db.transaction(['users'], "readwrite"); 
    //get object store
        var myusers = mytransaction.objectStore('users'); 
        var request = myusers.add(new getUser('admin','Shawn','Smith-Chao','admin'));  
        request.addEventListener('success',showUsers);   
    //Locally store that admin as been created  
        var admin = 'admin'; 
        var value = 'added';
        newItem(admin,value); 
}


//--------Retrieve User Date---------//
function getLogin(){
    alert('getLogin launched');
    var user = logUser.value;
    var pass = logPass.value;  
    alert('User: '+user+'  Pass: '+pass+"   sent to loginCheck");
    loginCheck(user,pass);
    alert ('user/pass checked');
}

function loginCheck(user,pass){
    var transaction = db.transaction(['users']);   
    var mystore = transaction.objectStore('users');  
    alert('User table opened');
    var request = transaction.get(user);
    alert('passed the get user request');
    request.onerror = function (event){
        alert("username does not exist");
    };
    request.onsuccess =function (event){
         alert('request was successful');
        /*alert("Welcome "+ request.result.userName);*/
        //run function populating all fields

    }
}

我在start(e)函数中发出警报,似乎在显示用户/通过的警报后立即调用。我环顾四周,我无法弄清楚是什么一直在呼唤它。

此外,如果我将loginCheck更改为此,则会运行警报并且代码会进一步发出警报('user / pass checked');但然后开始(e)再次被召唤。

1 个答案:

答案 0 :(得分:1)

indexeddb API异步工作,这就是警报不按照您的想法显示的原因。因为API是异步的,所以在等待异步调用完成时,所有其他代码都会执行。