php The solution to the garbled ajax post: first open the corresponding PHP file; then set the contentType; then set the encoding format of the page; and finally convert the SQL server database encoding.
Recommended: "PHP Video Tutorial"
ajax php POST method to send data (solve the backend Chinese garbled characters problem)
The front-end Ajax calls the interface, and the back-end receives the data and saves it in the database.
Note that contentType must be set like this.
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) } }) }
The backend accepts:
The encoding format of the page is utf-8, and the SQL server database is gbk. Pay attention to the conversion, otherwise the insertion will be garbled.
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); } }
The above is the detailed content of How to solve the garbled problem of php ajax post. For more information, please follow other related articles on the PHP Chinese website!