php ajax post亂碼的解決辦法:首先開啟相應的PHP檔案;然後設定contentType;接著設定頁面的編碼格式;最後轉換SQL server資料庫編碼即可。
推薦:《》
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 亂碼問題的詳細內容,更多請關注TW511.COM其它相關文章!