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


How to get UTF-8 format data through ajax

对不起,如果我问了一个愚蠢的问题,但我真的需要一个解决方案。我正在使用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 获取它时,我得到的是一系列问号 (??????)。如何通过 ajax 以与最初存在的格式相同的格式请求数据。

假设你的文件确实是一个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"?>

尝试使用 utf8-encode() 像,

echo utf8_encode($sqlitedata);

如果您使用的是jquery则将 $.ajax() 与contentType option一起使用,这default像,

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);
         }
     });
}

在头标签之间放置这个

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

如果您在 php 页面中使用任何查询,请在查询之前放置此查询

mysql_query('SET CHARACTER SET utf8');
$result1 = mysql_query("SET NAMES utf8");