ajax自动保存用户的输入

来源:互联网 发布:合肥java程序员工资 编辑:程序博客网 时间:2024/05/02 04:56

  在某本书上看到的,就是用户写文章时,每隔一定的时候,自动把用户的文章用cookie保存起来,也不失为一个办法,可以参考下.

update.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
var ajax=new AJAXRequest();
function temp() {
 var obj=document.getElementById("aj").value;
 if(obj){
 ajax.postf(
              "p",
               function(obj) {},
              "update.php",
              "POST" );
 }else{
 var obj2=getCookie("content");
 alert(obj2);
 document.getElementById("aj").value=obj2;
 }
}
setInterval("temp();", 3000);
 function setCookie(name,value)
 {
   var Days = 3;
   var exp  = new Date();  
   exp.setTime(exp.getTime() + Days*60*60*1000);
   document.cookie = name + "="+ encodeURIComponent(value)+";expires="+ exp.toGMTString();
 }
 function getCookie(name)
 {
   var arr = document.cookie.match(new RegExp("(^|)"+name+"=([^;]*)(;|$)"));
   if(arr != null) return decodeURIComponent(arr[2]);
   return
 null;
 }
 function delCookie(name)
 {
   var exp = new Date();
   exp.setTime(exp.getTime() - 1);
   var cval=getCookie(name);
   if(cval!=null) document.cookie=name+"="+cval+";expires="+exp.toGMTString();
 }
</script>
</head>

<body>
<form action="update.php" method="post" id="p">
<p>
  <textarea name="content" cols="50" rows="10" id="aj"></textarea>
</p>
<p>
<input type="hidden" name="action" value="save" />
<input name="" type="submit" value="提交信息" style="margin-top:20px;width:250px;height:40px;"/>
</p>
</form>
</body>
</html>

 

 

update.php
 <?php
header("content-Type: text/html; charset=UTF-8");
if($_POST['action'] == 'save') {
 $content   = $_POST['content'];
 // 暂时把提交的数据保存到COOKIE
 $cookietime=time()+7200;
 setcookie('content',$content,$cookietime);
    echo  $content;
}?>

原创粉丝点击