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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛