jquery的处理
var stu={
name:"tom",
age:22,
sex:true
};
$.ajax({
type : "POST",
url : "http://localhost:9000/index.php",//此处为跨域请求
contentType: "application/json; charset=utf-8",//Content-Type请求头的加入
data: JSON.stringify(stu),
dataType: "json",//将返回的数据,进行Json parse操作
success : function(result) {
console.log(result) //返回的数据解析成为js 对象
}
});
php的处理部分:
<?php
//跨域请求的处理头
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers: accept,x-requested-with,Content-Type');
//返回头(对jquery并不是必须,但针对于通用性,最好设置)
header('Content-Type:application/json; charset=utf-8');
//php7以后,唯一的方式来获取"raw request body"
$data = file_get_contents('php://input');
//$data数据类型为string,可以解析为关联数组
//$arry= json_decode($data,true);
//$arry["age"]=90;
//也可解析为stdClass对象
$student=json_decode($data);
$student->name="mikeLiu";
//将关联数据或者php对象,以json的形式返回
echo json_encode($student);