2017-07-30 49 views
0

下面是我發現的一些代碼,我認爲這是我答案的關鍵,但我還沒有完全理解它。自動保存LAST KeyUp只有JQuery,PHP,MySQL。怎麼樣?

jQuery autoSave v1.0.0

/* 
jQuery autoSave v1.0.0 - 2013-04-05 
(c) 2013 Yang Zhao - geniuscarrier.com 
license: http://www.opensource.org/licenses/mit-license.php 
*/ 
(function($) { 
    $.fn.autoSave = function(callback, ms) { 
     return this.each(function() { 
      var timer = 0, 
       $this = $(this), 
       delay = ms || 1000; 
      $this.keyup(function() { 
       clearTimeout(timer); 
       var $context = $this.val(); 
       if(localStorage) { 
        localStorage.setItem("autoSave", $context); 
       } 
       timer = setTimeout(function() { 
        callback(); 
       }, delay); 
      }); 
     }); 
    }; 
})(jQuery); 

下面我有什麼我目前研究工作示例。我想修改這段代碼,以便它在KeyUp上觸發,而不是每隔幾秒鐘,而不管用戶是否更新。

的index.php

<html> 

<head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
    <meta charset="utf-8"> 
    <title>Webslesson Tutorial</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
</head> 

<body> 
    <div class="container"> 
    <br> 
    <h2 align="center">Auto Save Data using Ajax, Jquery, PHP and Mysql</h2> 
    <br> 
    <div class="form-group"> <label>Enter Post Title</label> 
     <input type="text" name="post_title" id="post_title" class="form-control"> </div> 
    <div class="form-group"> <label>Enter Post Description</label> <textarea name="post_description" id="post_description" rows="6" class="form-control"></textarea> </div> 
    <div class="form-group"> 
     <button type="button" name="publish" class="btn btn-info">Publish</button> 
    </div> 
    <div class="form-group"> 
     <input type="hidden" name="post_id" id="post_id"> 
     <div id="autoSave"></div> 
    </div> 
    </div> 
    <script> 
    $(document).ready(function(){ 
      function autoSave() 
      { 
       var post_title = $('#post_title').val(); 
       var post_description = $('#post_description').val(); 
       var post_id = $('#post_id').val(); 
       if(post_title != '' && post_description != '') 
       { 
        $.ajax({ 
         url:"save_post.php", 
         method:"POST", 
         data:{postTitle:post_title, postDescription:post_description, postId:post_id}, 
         dataType:"text", 
         success:function(data) 
         { 
           if(data != '') 
           { 
            $('#post_id').val(data); 
           } 
           $('#autoSave').text("Post save as draft"); 
           setTimeout(function(){ 
            $('#autoSave').text(''); 
           }, 5000); 
         } 
        }); 
       }    
      } 
      setInterval(function(){ 
       autoSave(); 
       }, 10000); 
    }); 
    </script> 
</body> 

</html> 

save_post.php

<?php 
$connect = mysqli_connect("mysqlserver", "database", "password", "databasename"); 
if(isset($_POST["postTitle"]) && isset($_POST["postDescription"])) 
{ 
    $post_title = mysqli_real_escape_string($connect, $_POST["postTitle"]); 
    $post_description = mysqli_real_escape_string($connect, $_POST["postDescription"]); 
    if($_POST["postId"] != '') 
    { 
    //update post 
    $sql = "UPDATE tbl_post SET post_title = '".$post_title."', post_description = '".$post_description."' WHERE post_id = '".$_POST["postId"]."'"; 
    mysqli_query($connect, $sql); 
    } 
    else 
    { 
    //insert post 
    $sql = "INSERT INTO tbl_post(post_title, post_description, post_status) VALUES ('".$post_title."', '".$post_description."', 'draft')"; 
    mysqli_query($connect, $sql); 
    echo mysqli_insert_id($connect); 
    } 
} 
?> 

回答

0

我做這些的方式是與我稱之爲滾動超時,基本的超時大幹快上的每個復位鍵按這樣的事情,這是有點psudo ish,但它應該給你的想法

 var timeout; 

    $('body').on('keyup', '.field', function(event){ 
      if(timeout) 
       clearTimeout(timeout); 

      timeout = setTimout(function(event){ 
       autosave(); 
      },400); //i find 400 milliseconds works good 

    }); 

    function autosave(){ 
     .... 
    } 

所以基本上會發生什麼是在第一個鍵盤上,我們設置超時。然後,如果在400毫秒內按下另一個鍵,我們取消超時並設置一個新的鍵。一旦用戶停止輸入更長時間然後超時,保存功能被觸發。

乾杯!

clearTimeout

https://www.w3schools.com/jsref/met_win_cleartimeout.asp

setTimeout的,你可以做些什麼來改善,這是存儲和放棄以前的AJAX

https://www.w3schools.com/jsref/met_win_settimeout.asp

的另一件事(XMLHttpRequest的)請求形成保存功能(特別是如果需要一些時間來保存它)

所以在s AVE功能

var timeout; 
var saveRequest; 

$('body').on('keyup', '.field', function(event){ 
    if(timeout) 
     clearTimeout(timeout); 
    if(saveRequest){ 
     saveRequest.abort(); 
     saveRequest = false; 
    } 

    timeout = setTimout(function(event){ 
     autosave(); 
    },400); //i find 400 milliseconds works good 
}); 


function autoSave(){ 
     .... 
     saveRequest = $.post(url, {}, function(data){ 
      ... 
     } 
     ... 
} 

這適用於同樣的想法,如果請求掛起,我們得到一個呼籲一個新的請求,那麼舊的請求,也沒有關係,因爲該數據已更新。所以我們可以取消這個請求並排隊一個新的請求。

XMLHttpRequest.abort()

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

我可能會做第一個,以及第一。如果需要很長時間才能完成保存,那麼可以考慮中止請求。

謝謝。

+0

等不及試試這個!因此,爲了澄清,在400ms標記內創建的每個實例在創建下一個實例之前會被銷燬,還是隻是創建沒有垃圾收集的新實例? – ASPiRE

+0

'clearTimeout(timeout)'會破壞以前的超時。 – ArtisticPhoenix

+0

我接受了您的答案,併發布了我的更新工作版本作爲答案供您參閱。你如何在我的答案中實現XMLHttpRequest.abort()?謝謝你的一切。 – ASPiRE

0

這是一些額外的工作版本。

$(document).ready(function() { 

     var timer; 

     $('#post_title').keyup(function() { 

      if (timer) { 
       clearTimeout(timer); 
      } 

      timer = setTimeout(function(event) { 
       autoSave(); 
      }, 1000); //wait 1000 milliseconds before triggering even. 

     }); 

     function autoSave() { 
      var post_id = $('#post_id').val(); 
      var post_title = $('#post_title').val(); 
      var post_description = $('#post_description').val(); 
      //if(post_title != '' && post_description != '') 
      if (post_title != '') { 
       $.ajax({ 
        url: "save_post.php", 
        method: "POST", 
        data: { 
         postTitle: post_title, 
         postDescription: post_description, 
         postId: post_id 
        }, 
        dataType: "text", 
        success: function(data) { 
         if (data != '') { 
          $('#post_id').val(data); 
         } 
         var time = showTime(); 
         $('#autoSave').text("Draft Autosaved " + time).show(); 
         $('#autoSave').fadeOut(3000); 
        } 
       }); 
      } 
     } 
    }); 

    function showTime() { 

    var timeNow = new Date(); 
    var hours = timeNow.getHours(); 
    var minutes = timeNow.getMinutes(); 
    var seconds = timeNow.getSeconds(); 
    var timeString = "" + ((hours > 12) ? hours - 12 : hours); 
    timeString += ((minutes < 10) ? ":0" : ":") + minutes; 
    timeString += ((seconds < 10) ? ":0" : ":") + seconds; 
    timeString += (hours >= 12) ? " P.M." : " A.M."; 
    return timeString; 

    }