javascript - XMLHttpRequest 响应类型和 JSON

标签 javascript php json ajax xmlhttprequest

我有一个简单的 PHP 脚本,它返回一个简单的 JSON 响应:

$data=array('a'=>'apple');
header('Content-Type: application/json');
print json_encode(array($date));

使用 JavaScript,我尝试读取数据:

var url='…';
var xhr=new XMLHttpRequest();
xhr.open('get', url, true);
xhr.send(null);
xhr.onreadystatechange=function() {
    if(this.readyState==4) {
        alert(this.responseText);
        alert(this.responseType);
    }
};

代码大部分都有效,但我无法获取 responseType 属性的任何内容。我原以为它是 json 但任何东西都会有帮助。

我认为合适的 mime 类型可以完成这项工作。我在 Firefox 中尝试过,它通常具有很好的支持,在 Safari 中也是如此。

我错过了什么?

最佳答案

responseType 不是服务器响应的 MIMEType。您可以在发送 XMLHttpRequest 之前设置它,以便在响应到达时影响 response 属性的类型。详情见XMLHttpRequest Level 1 at W3C.org

您可以通过 this.getResponseHeader("Content-Type") 访问服务器响应的 MIMEType。

关于javascript - XMLHttpRequest 响应类型和 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32473892/

相关文章:

javascript - 放大/缩小时,Leaflet map 和图层不会同时移动

javascript - 如何获取表格的点击 td 索引?

javascript - 来自 Controller 的 Angular 动画

javascript - 如何只重新加载页面一次而不重复加载

php - 如何使用 phpmyadmin 导出 MySQL 中的特定列?

用于验证测试的 Json Schema 数据集

javascript - JSON.stringify 用空格替换加号

python - 将 django 升级到 1.6.5 后出现 django object is not JSON serializable 错误

javascript - 如何将 jquery 拖放转换为 Angular ?

PHP 随机字符串生成器