如何解决php ajax post 乱码问题
程序员文章站
2022-03-13 21:50:02
...
php ajax post乱码的解决办法:首先打开相应的PHP文件;然后设置contentType;接着设置页面的编码格式;最后转换SQL server数据库编码即可。
推荐:《PHP视频教程》
ajax+php POST方法发送数据(解决后端中文乱码问题)
前端Ajax调用接口,后端接收数据保存数据库。
注意contentType一定这样设置。
if(isSuccess){ var token = sessionStorage.token; $.ajax({ type:'post', url:'../../api/container/'+token+'/addContainerDamageReport', contentType:'application/x-www-form-urlencoded;charset=utf-8', data:{'containerName':'HJSY'+containerName,'username':username,'description':descript,'damageTime':damageTime ,'reportTime':reportTime,'damageLevel':badLevel,'damageType':badType}, cache:false, dataType:'json', success:function(data){ $('#submit').attr('data-dismiss',"modal"); console.log(data) } }) }
后端接受:
页面的编码格式utf-8,SQL server数据库是gbk,注意转换,否则插入进去是乱码。
if($action=='addContainerDamageReport') { $ret["IsInsert"]=false; if($conn!=false) { $containerName = isset($_POST['containerName'])?$_POST['containerName']:""; $username = isset($_POST['username'])?$_POST['username']:""; $description = isset($_POST['description'])?iconv("utf-8","gbk",$_POST['description']):""; $damageTime = isset($_POST['damageTime'])?$_POST['damageTime']:""; $reportTime = isset($_POST['reportTime'])?$_POST['reportTime']:""; $damageLevel = isset($_POST['damageLevel'])?$_POST['damageLevel']:""; $damageType = isset($_POST['damageType'])?$_POST['damageType']:""; $SqlString="INSERT INTO [Mopex].[dbo].[ContainerDamageReport] ([Id],[ContainerName],[DamageTime],[ReportTime] ,[DamageLevel],[CheckName],[DamageType],[Description] ,[ReportName],[Status],[CheckTime]) values(newId(),'".$containerName."','".$damageTime."','".$reportTime."', '".$damageLevel."','admin','".$damageType."','".$description."','".$username."', 0,'1900-01-01 00:00:00.0000000')"; OpenDB($conn,$databasename); $rs_insert = DB_Query($conn,$SqlString); if($rs_insert != false) { $ret["IsInsert"]=true; $DataList[0]=array('containerName'=>$containerName,'username'=>$username, 'damageTime'=>$damageTime,'reportTime'=>$reportTime,'damageLevel'=>$damageLevel,'damageType'=>$damageType, 'description'=>$description,'status'=>'0'); } DB_Close($conn); } }
以上就是如何解决php ajax post 乱码问题的详细内容,更多请关注其它相关文章!
上一篇: 介绍一个力软敏捷开发框架
下一篇: PHP中使用curl取得HTTP状态码