我有一个简单的 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/