Ajax IndexedDB Delete Current Sucesfull Upload

后端 未结 2 1709
萌比男神i
萌比男神i 2021-01-23 12:01

I posted something similar yesterday but it works but only deleted the last object in the data.

What I want to happen

This ajax upload will be h

相关标签:
2条回答
  • 2021-01-23 12:26

    The only solution I found worked with this was to send the Key via ajax to php then delete from that.

    HTML

    var passData = {     
                            .......
                            key: res.key,
                        };
    
    .....
    
       $.ajax({
                           url: "yourscript.php",
                           type: "post",
                           data: {
                               "json": passData 
                           },
    
                           success: function(JsonData) {
    
                               jsonKey = JSON.parse(JsonData);
    
    
                               //Delete item once successfull 
                               var t = db.transaction(["data"], "readwrite");
                               var request = t.objectStore("data").delete(parseInt(jsonKey.key));
                               t.oncomplete = function(event) {
                                console.log('item deleted', jsonKey.key);
                               };
    
    
    
                           }
    

    PHP

        $data = $_POST['json'];
    
    
        $returnKey =  json_encode(
                        array(
                                'key' => $data['key']
                        )
        );
    
    0 讨论(0)
  • 2021-01-23 12:29

    It sounds like you have a scope issue with passData. Inside of your loop, but before you defined var passData = ... try wrapping the codeblock with an anonymous function:

    (function() {
       /* Your code here */
    }());
    

    That should prevent passData from leaking into the global scope, which seems to be why your IDB code only works on the last loop. (passData is being redefined each time before your AJAX response is able to complete.)

    Update: There is no loop, you're dealing with callbacks. What I see happening is that you're redefining your onsuccess handler on each Ajax request (and overwriting all values but the last), reusing the same transaction. Try moving this transaction code into the success callback for the AJAX request:

    //Get Database 
     var transaction = db.transaction(["data"], "readonly");
     var objectStore = transaction.objectStore("data");
     var cursor = objectStore.openCursor();
    

    That will create a closure and commit your delete transaction on each response. That means one transaction per AJAX request, and one onsuccess callback per AJAX request (with no redefining).

    0 讨论(0)
提交回复
热议问题