如何使用普通javascript发送dataType JSON
。在Jquery中,按照以下方式成功工作并返回数据。
$.ajax({
url:"fetch.php",
method:"POST",
data:{sts:'student'},
dataType:"JSON",
success: function(data){
},
error: function(data) {
console.log(data);
}
});
但是在切换到纯JavaScript时。我添加了http.responseType = 'json';
var http = null;
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}
else{
http = new ActiveXObject('Microsoft.XMLHTTP');
}
http.open('POST','fetch.php',true);
http.responseType = 'json';
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
var data = http.responseText;
}
}
http.send('sts=student');
但是抛出错误;
InvalidStateError:仅当responseType为时,responseText才可用 ”或“文本”。
我已更改http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
到http.setRequestHeader('Content-type','application/json');
,但有相同的错误。