编程技术

如何解决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#tyuanma.cn删除

php mysql查询记录数的方法

云服务器推荐