【发布时间】:2018-03-20 14:43:08
【问题描述】:
我是编程新手。 我有一个通过蓝牙连接到应用程序的传感器。应用程序将数据发送到云服务。我从云服务中获得了一个链接,其中包含 json 格式的数据。现在我希望这些数据显示在我的网站上,但它的跨域和我所做的任何事情都会显示 401(未经授权)。
<html>
<head>
<title>Sensor</title>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>Sensor</h1>
<button onclick="myFunctionPost()">Start</button>
<div id="result" style="color:red"></div>
<script>
function myFunctionPost() {
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('https://thetablewheremydatais$format=json').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>
【问题讨论】:
-
401表示您必须进行身份验证。 -
我知道但我不知道怎么做,我用 client.setRequestHeader("Authorization", "Basic" + btoa("username:password"));
-
您提到的是基本身份验证,但可能不是服务器所期望的?
标签: javascript json xmlhttprequest cross-domain jsonp