在客户端我们可以用ajax这样来提交post数据,格式不是传统的
a=1&b=1
而是 {"a":"1","b":"1"}
<form id="buyform">
<input type="text" name="a" value="1">
<input type="text" name="b" value="1">
</form>
<script>
$("#buyform").submit(function (envent){
envent.preventDefault();
var fields = $('#buyform').serializeArray();
var obj = {}; //声明一个对象
$.each(fields, function(index, field) {
obj[field.name] = field.value; //通过变量,将属性值,属性一起放到对象中
})
$.ajax({
type: "post",
url: "do.php",
async: true,
contentType: 'application/json',
dataType: 'JSON',
data: JSON.stringify(obj),//将对象转为json字符串
success: function(obj) {
}
});
});
</script>
php这样来接收
function RecvPostData()
{
if (empty($_POST) && false !== strpos($_SERVER['HTTP_CONTENT_TYPE'], 'application/json')) {
$content = file_get_contents('php://input');
$post = (array)json_decode($content, true);
} else {
$post = $_POST;
}
return $post;
}
$_POST=RecvPostData();
$aa=$_POST['a'];
$bb=$_POST['b'];