jQuery的Cookie封装,与PHP交互

来源:互联网 发布:电视直播软件live官网 编辑:程序博客网 时间:2024/06/07 04:05

首先,用到两个jQuery函数,JSON.parse(Json字符串转对象)和JSON.stringify(对象转JSON字符串)

我这里的分成两次封装,因为数据不在一个页面里。

这是第一个页面:

$(".color-gray").click(function(){var detail = new Object();//自定义一个空对象 将获取的参数放入这个对象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



                                             
0 0