jQuery的Cookie封裝,與PHP互動的簡單實現_jquery

來源:互聯網
上載者:User

首先,用到兩個jQuery函數,JSON.parse(Json字串轉對象)和JSON.stringify(對象轉JSON字串)

我這裡的分成兩次封裝,因為資料不在一個頁面裡。

這是第一個頁面:

$(".color-gray").click(function(){     var detail = new Object();//自訂一個Null 物件 將擷取的參數放入這個對象     detail.userName = $('input[data-node="userName"]').val();     detail.userSex = $(".userSex").val();     detail.detail = $('input[data-node="address"]').val();     detail.phone = $('input[data-node="telephone"]').val();     detail.id = $('input[name="address_id"]').val();          $.cookie("info", JSON.stringify(detail));//用JSON.stringify函數將對象轉成JSON字串,放入Cookie裡。     location.href = "{pigcms{:U('User/adres_map')}";   }); 

第二個頁面:

$(".addresslist").live('click', function(){     info = JSON.parse($.cookie('info'));//因為第一個頁面中封裝的Cookie是JSON字串,這裡要先轉成對象。再將本頁面的資料放進去。     info.name = $(this).attr("address");     info.longitude = $(this).attr("lng");     info.latitude = $(this).attr("lat");          $.cookie('info', JSON.stringify(info));//放進去之後,重新封裝     location.href = "{pigcms{:U('User/add_adres')}&address_id="+info.id;   }); 

這樣,頁面運行之後,Cookie中就有了上面的資料。

最後,jQuery清空Cookie,

$(".icon-arrow-left2").click(function(){     $.cookie('info', 0);    }); 

最最後,PHP方法互動,

<pre name="code" class="php">/* 執行編輯 */   public function edit_adres(){     $id = $_POST['address_id'];     $params['name']     = $_POST['name'];     $params['sex']     = $_POST['sex'];     $params['address']   = $_POST['address'];     $params['detail']    = $_POST['detail'];     $params['phone']    = $_POST['phone'];     $params['uid']     = $this->_uid;     $params['longitude']  = $_POST['longitude'];     $params['latitude']   = $_POST['latitude'];     $params['create_time'] = time();          if( !$id ){       if($returnId=D('表名')->data($params)->add()){         if(IS_AJAX){           setcookie('info');           $this->ajaxReturn($returnId, '添加成功', 1);exit;         }         } else {         $this->error('添加失敗,請重試!');       }     } else {       $where['address_id'] = $id;       if(D('表名')->where($where)->data($params)->save()){         if(IS_AJAX){           setcookie('info');           $this->ajaxReturn($id, '編輯成功', 1);exit;         }       } else {         $this->error('編輯失敗,請重試!');       }     }   } 

最最最後,補充一下,

如果需要在頁面輸出已經寫好的cookie,需要先執行個體化一下,

detail = JSON.parse($.cookie('info')); 

然後才能這樣使用,

detail.name 

以上就是小編為大家帶來的jQuery的Cookie封裝,與PHP互動的簡單實現全部內容了,希望大家多多支援雲棲社區~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.