protected function json($data, $type = 'ok'){
    pgExit(json_encode(array('status' => $type, 'data' => $data)));
}

//common functions
function pgExit($msg = ''){    
    exit($msg);
}

phpgrace 框架调用this->json函数返回的数据头是 Content-Type: text/html; charset=utf-8
在接口调用时,判断是有错误的,例如下面的ajax调用,永远执行else,因为res.status是未定义对象

$.ajax({
    url:"https://xxx.xxx.com/addOrder",
    type:"post",
    data:{myprice:myprice,myproduct:myproduct,mykey:mykey},
    success:function(res){
        console.log(res);
        if(res.status == 'error'){
                alert('错误');
                Long.diolog({
                    title: "订单号获取失败",
                    text: '请尝试重新下单,或联系人工客服处理',
                    btn1text: "确定",
                    btn1callback: function () {
                    window.location.href = "<? echo u(PG_C,'pay'); ?>";
                    }
                })
            }else{
                alert(res);
            }                
    }
});

如何解决这种问题呢?
可以在if(res.status == 'error'){ 判断之前,添加代码res = JSON.parse(res) 即可。

也可以修改框架函数,pgExit函数添加head头,强制输出json类型

function pgExit($msg = ''){
    header('Content-Type:application/json; charset=utf-8');    
    exit($msg);
}

处理这个问题把我搞死了,感谢我嫖哥发现这个问题,么么哒。

php返回json,xml,JSONP等格式的数据

返回json数据

header('Content-Type:application/json; charset=utf-8');
$arr = array('a'=>1,'b'=>2);
exit(json_encode($arr));
注意:如果不加header直接输出json_encode的值的话,返回的是字符串不是对象,js那边就需要先eval('('+data+')')转化为对象,在取值

返回xml数据

header('Content-Type:text/xml; charset=utf-8');
exit($xml);

thinkphp如何返回各种数据

$this->ajaxReturn (json_encode($arr),'JSON');
$this->ajaxReturn (json_encode($arr),'JSONP');
$this->ajaxReturn (json_encode($arr),'XML');

json_encode有个参数禁止unicode编码
JSON_UNESCAPED_UNICODE
json_encode('中文',JSON_UNESCAPED_UNICODE);

默认中文编码
header('Content-Type:application/json; charset=gbk');
$data = $db->select($sql);
$data = json_encode($data);
$data=preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'gbk', pack('H4', '\\1'))", $data);
exit($data);

参考:https://www.cnblogs.com/lovebing/p/9289076.html

Last modification:June 17, 2020
如果觉得我的文章对你有用,请随意赞赏