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

Let*_*see 6 javascript php ajax jquery utf-8

对不起,如果我问一个愚蠢的问题,但我真的需要一个解决方案.我正在使用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>
Run Code Online (Sandbox Code Playgroud)

这是我的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';
             } 
?>
Run Code Online (Sandbox Code Playgroud)

现在问题是我的文件中的数据是UTF-8格式,但是当我试图通过ajax获取它时,我得到的是一系列问号(??????).我如何通过ajax以最初存在的相同格式请求数据.

mik*_*kun 8

假设你的文件确实是一个xml文件,假设发出请求的页面是utf8,

然后在你echo的PHP文件中的任何东西之前:

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

为了在xml中提供额外的安全性:

<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)

编辑你也可以这样做:

header('Content-type: text/xml');
Run Code Online (Sandbox Code Playgroud)

<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)


Roh*_*mar 5

尝试使用utf8-encode() 之类的,

echo utf8_encode($sqlitedata);
Run Code Online (Sandbox Code Playgroud)

如果您正在使用jquery,然后使用$阿贾克斯()contentType optiondefault类似,

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);
         }
     });
}
Run Code Online (Sandbox Code Playgroud)