与php后台的交互(和解决中文编码问题)

来源:互联网 发布:58同城上的淘宝美工 编辑:程序博客网 时间:2024/05/03 20:59
json格式在开发中用的十分广泛。在php中json_encode函数可以直接将数组转成 json格式,十分方便。但是有可能你在使用json_encode函数时,无奈的发现中文被编码成null了。原来json只支持转义utf-8编码格式的中文。php数组使用json_encode函数中文被编码成null的原因是转义gbk 或者别的编码时,中文被忽略了。一般出现在文档编码或者输出的内容编码是非UTF-8时,也就是说,GBK或者GB2312的中文,就会出现编码失败的现象。
php数组使用json_encode函数中文被编码成null的原因和解决办法,如果你的程序是采用utf-8编码,请确保文件保存为utf-8 无bom格式,如果你的程序是gbk的,可以先转成utf-8编码后在使用json_encode函数。
<?php header('Access-Control-Allow-Origin:*'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); header("Content-Type: charset=UTF-8");$json  = array(   array('title' => iconv('gb2312','utf-8','这里是中文标题'),'childtitle' => iconv('gb2312','utf-8','这里是中文标题'),   ),   array('title' => iconv('gb2312','utf-8','这里是中文标题'),'childtitle' => iconv('gb2312','utf-8','这里是中文标题'),   ));echo json_encode($json);?>

前台代码:(这里用的是axios请求插件,项目为vue-cli脚手架搭建的vue.js项目)

<script type="text/babel">export default{created:function(){        this.$http({        method:'GET',        url:'http://localhost/quality.php'        }).then((response) => {this.data = response.dataconsole.log(this.data[0].title)        },(response) => {        alert('error')        })},data(){return{data:[]}}}</script>