php返回json对象给前端

版权声明:本文为博主原创文章,未经博主允许是可以随意转载的哦!!! https://blog.csdn.net/qq_27517377/article/details/86686367

    开发中经常碰到php返回json数据给前端的情况,直接echo json_encode('xxxx'); 这样子返回的话,默认:Content-Type:text/html; charset=UTF-8 是这样的,那么我们只需要改变header头为json的类型,那么就可以实现php返回的数据直接是json类型了。

/**
 * ajax数据返回json数据成功
 */
function apiSuccess($msg="操作成功",$code=2000,$data=[],$redirect_url='')
{
  header('Content-Type:application/json');//加上这行,前端那边就不需要var result = $.parseJSON(data);
  $ret = ["code" => $code,"msg" => $msg, "data" => $data,'redirect_url'=>$redirect_url];
  return json_encode($ret,JSON_UNESCAPED_UNICODE);
}

前端那边需要var result = $.parseJSON(data);

$.post("/admin/group/edit",{id:id,name:name,status:status,time:time},function(result){
    //var result = $.parseJSON(data);
    layer.msg(result.msg);
    if(result.code==2000){
        setTimeout(function(){window.location.href="/admin/group/index";},500)
    }
});

在php端返回数据的时候指定json类型的header,header('Content-Type:application/json');前端就可以直接操作对象了,so,小伙伴们学会了怎么用php返回json对象了吧!

猜你喜欢

转载自blog.csdn.net/qq_27517377/article/details/86686367