我已经对谷歌和许多其他页面进行了研究,我可以在这里通过 traccar api 提取数据,所以我接下来研究如何使用它,最后通过 mvalverde在这里找到这个答案。在那篇文章中,他编写了一些代码,如下所示:
// find All devices - GET request
var result = HTTP.call(
"GET",
'http://your_domain:8082/api/devices/',
{
auth: 'email@xyz.com:password' ,
params: {
}
}
);
// add device
var name = 'name your device';
var uniqueId = '122323223232'; // usually this is the device imei
var result = HTTP.post(
'http://your_domain:8082/api/devices/',
{
auth: 'email@xyz.com:password' ,
data:{
groupId:null,
id: null,
lastUpdate:null,
status:'',
name:name,
uniqueId:uniqueId
}
}
);
他说这是javascript,所以我尝试用javascript方式实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>try traccar api</title>
</head>
<body>
<script type="text/javascript">
var result = HTTP.call(
"GET",
'http://103.23.20.176:8082/api/devices/',
{
auth: 'email:password' ,
params: {
}
}
);
console.log(result);
</script>
</body>
</html>
但我在控制台中收到错误。我怀疑它不是纯 javascript,如果可以的话,你可以指导我使用 javascript 编写实现。所以任何人都可以帮我解决这个问题。
ps:我还是js领域的菜鸟
== 更新 ==
感谢 anton tananaev,我解决了这个问题,如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>try traccar api</title>
</head>
<body>
<script src="js/jquery-2.2.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
$.ajax({
type: 'get',
url: 'http://103.23.20.176:8082/api/devices/',
headers: {
"Authorization": "Basic " + btoa("admin:admin")
},
success: function (response) {
console.log(response);
}
});
</script>
</body>
</html>
还有1个问题,如何发布数据?我尝试这样:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>try traccar api</title>
</head>
<body>
<script src="js/jquery-2.2.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
var name = "Bus 2";
var uid = "1212321233";
$.ajax({
type: 'post',
url: 'http://103.23.20.176:8082/api/devices/',
headers: {
"Authorization": "Basic " + btoa("email:pass")
},
data:{
id:null,
name:name,
uniqueId:uid,
groupId:null,
status:'',
lastUpdate:null
},
success: function (response) {
console.log(response);
}
});
</script>
</body>
</html>
但我得到状态码 415 不支持的媒体类型。我在我的代码中错过了什么?
== CLOSED ==
下一个问题的最终代码在这里,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>try traccar api</title>
</head>
<body>
<script src="js/jquery-2.2.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
var name = "Bus 3";
var uid = "1243232133";
$.ajax({
type: 'post',
url: 'http://103.23.20.176:8082/api/devices/',
headers: {
"Authorization": "Basic " + btoa("email:pass")
},
contentType:"application/json",
data:JSON.stringify({
name:name,
uniqueId:uid
}),
success: function (response) {
console.log(response);
}
});
</script>
</body>
</html>
谢谢,我解决了我的问题:)