我正在尝试使用Javascript从我的服务器获取json数据,然后我按照提供的解决方案here。但它对我不起作用。我发现xhr.onload = function()不能在我的情况下运行。如何理解?
<!DOCTYPE html>
<html>
<body>
<div id="result" style="color:red"></div>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://qlin.parseapp.com/version2/myres.txt').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
</script>
</body>
</html>