首页 >后端开发 >PHP问题 >如何解决php ajax post 乱码问题

如何解决php ajax post 乱码问题

藏色散人
藏色散人原创
2020-10-10 09:54:191673浏览

php ajax post乱码的解决办法:首先打开相应的PHP文件;然后设置contentType;接着设置页面的编码格式;最后转换SQL server数据库编码即可。

如何解决php ajax post 乱码问题

推荐:《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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn