dte29947 2013-11-11 04:43
浏览 305
已采纳

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

Sorry if i am asking a silly question but i really need a solution for it.I am requesting for some data using ajax and the script is

<!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>

and this is my php script

<?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';
             } 
?>

Now the problem is that the data in my file is in the UTF-8 format but when i try to get it through ajax then what i get is a series of question marks (??????) . How can i request for the data through ajax in the same format in which it originally exists.

  • 写回答

3条回答 默认 最新

  • doucong4535 2013-11-11 04:49
    关注

    asuming your file is indeed a xml file, assuming the page making the request is utf8,

    then before you echo anything in your php file :

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

    for extra safety in your xml :

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

    edit you can do that as well :

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

    with

    <?xml version="1.0" encoding="UTF-8"?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置