我們先了解一下什麼是序列化,看了一篇文章,在PHP中的作用是可以將我們的數組轉爲對象。
反序列化那麼就是將對象在轉爲數組。
例子看一下可以 ----> 通過ajax將表單值傳入後臺請看後面(可跳過這裏內容)
$sites = array('Google'=>'$ser', 'Runoob'=>'1111', 'Facebook'=>333);
//序列化
$serialized_data = serialize($sites);
//得到 a:3:{s:6:"Google";s:4:"$ser";s:6:"Runoob";s:4:"1111";s:8:"Facebook";i:333;}
//反序列化
$a = unserialize($serialized_data);
//得到
// array(3) {
// ["Google"]=>
// string(4) "$ser"
// ["Runoob"]=>
// string(4) "1111"
// ["Facebook"]=>
// int(333)
// }
通過ajax將數據傳入後臺
這裏的後臺我用的是thinkphp沒用用原生php。
前端HTML內容:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<title>Document</title>
</head>
<body>
<form method="post" name="forms">
<input type="checkbox" name="a" value="1">
<input type="checkbox" name="b" value="2">
<input type="checkbox" name="c" value="3">
<input type="checkbox" name="d" value="4">
<input type="checkbox" name="e" value="5">
<input type="checkbox" name="f" value="6">
<input type="checkbox" name="g" value="7">
<button onclick="ceshi()" type="button">tijiao</button>
</form>
</body>
</html>
<script>
function ceshi() {
$.ajax({
type: 'POST',
url: "{:url('index/index/test')}",
data: $('form').serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function () {
console.log("error");
}
});
}
</script>
index控制器內容:
<?php
namespace app\index\controller;
use think\Log;
use think\Controller;
use think\Db;
class Index extends Controller
{
public function test()
{
$all = input();
return json($all);
}
}
這樣我們將多選框的數據返回給了前端。這裏返回前端的是一個對象的形式。
下面我們將數據轉爲數組的格式
tp控制器代碼
<?php
namespace app\index\controller;
use think\Log;
use think\Controller;
use think\Db;
class Index extends Controller
{
public function test()
{
'a'=>input( 'a' ),
'b'=>input( 'b' ),
'c'=>input( 'c' ),
'd'=>input( 'd' ),
'e'=>input( 'e' ),
'f'=>input( 'f' ),
'g'=>input( 'g' ),
];
return json($data);
}
}
前端處理數據爲
<script>
function ceshi() {
$.ajax({
type: 'POST',
url: "{:url('index/index/test')}",
data: $('form').serialize(),
dataType: 'json',
success: function (data) {
console.log(data.a);
console.log(data.b);
console.log(data.c);
console.log(data.d);
console.log(data.e);
console.log(data.f);
console.log(data.g);
},
error: function () {
console.log("error");
}
});
}
</script>
序列化接收值的格式爲
c=3&g=7&a=1&d=4&b=2&f=6&e=5