如何通过ajax获取UTF-8格式数据

9

很抱歉如果我问了一个愚蠢的问题,但我真的需要解决方案。我正在使用ajax请求一些数据,脚本是:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
$url='http://localhost/path/to/the/php/script';
xmlhttp.open("GET",$url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

这是我的PHP脚本

<?php 

$sqlurl='/path/to/my/file';

 if(file_exists($sqlurl))
            {
                $sqlitedata= file_get_contents($sqlurl);

       echo $sqlitedata;
            }
            else {

           echo 'the file is not available right now';
             } 
?>

现在的问题是,我的文件中的数据是以UTF-8格式存储的,但是当我尝试通过ajax获取它时,得到的是一系列问号(??????)。我该如何在请求数据时保持原始格式不变?

3个回答

8

假设您的文件确实是一个XML文件,假设发出请求的页面是UTF8编码的,则在您的PHP文件中执行任何echo之前:

<?php header("Content-Type: application/xml; charset=utf-8"); ?>

为了在您的XML中提供额外的安全性:
<?xml version="1.0" encoding="UTF-8"?>

你也可以进行编辑:

header('Content-type: text/xml');

使用

<?xml version="1.0" encoding="UTF-8"?>

5

尝试使用utf8-encode(),例如:

echo utf8_encode($sqlitedata);

如果您正在使用jquery,则请使用带有contentType选项$.ajax(),它是默认的,例如:
function loadXMLDoc()
{
     $.ajax({
         type:"GET",
         url:"http://localhost/path/to/the/php/script",
         contentType: "application/x-www-form-urlencoded;charset=utf-8",
         success: function(data){
             $("#myDiv").html(data);
         }
     });
}

1
在标签之间放置此内容。
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

如果您在php页面中使用任何查询,请在查询之前添加以下内容。
mysql_query('SET CHARACTER SET utf8');
$result1 = mysql_query("SET NAMES utf8");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接