我想在地图的控制台中打印状态和其他变量 API。 我创建的XHR对象包含变量中的数据,但是当我打印时 xhr.status它说0.但在控制台当我打开XHR对象状态是 200。 我确实想打印从maps API返回的整个数据。我什至 启用CORS请求。
<button type="button" onclick="myFunction()">Submit</button></br>
</form>
<p id="demo"> hello</p>
<script>
function myFunction() {
var slat = document.getElementById("slat").value;
var slong = document.getElementById("slong").value;
var dlat = document.getElementById("dlat").value;
var dlong = document.getElementById("dlong").value;
//xhr object for sending request to maps api
var xhr=
createCORSRequest('GET',"https://maps.googleapis.com/maps/api/directions/json?
origin=75+9th+Ave+New+York,+NY&destination=Boston&key=My key was here");
if (!xhr) {
throw new Error('CORS not supported');
}
console.log(xhr); // seeing the xhr object
console.log(xhr.response); // trying to print xhr response but nothing is coming
console.log(xhr.status); // 0 is being displayed as status but 200 is there in xhr object
console.log(xhr.responseType);
}
答案 0 :(得分:1)
很可能你正在创建一个XMLHttpRequest;你需要提供onload
处理程序,你想要的属性将在处理程序中可用:
xhr.onload=function(e) {
console.log(xhr.response);
console.log(xhr.status);
console.log(xhr.responseType);
}
请注意,我假设您使用xhr.send()
发送邮件。
如果您查看Google提供的developer's guide,则响应json对象包含一个名为routes
的数组。您应该使用xhr.response.routes[0]
访问第一个路径,并且此json对象包含summary
和legs
数组属性,如下所示:
"routes": [ {
"summary": "I-40 W",
"legs": [ {
"steps": [ {
"travel_mode": "DRIVING",
"start_location": {
"lat": 41.8507300,
"lng": -87.6512600
},
"end_location": {
"lat": 41.8525800,
"lng": -87.6514100
},
"polyline": {
"points": "a~l~Fjk~uOwHJy@P"
},
"duration": {
"value": 19,
"text": "1 min"
},
"html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e",
"distance": {
"value": 207,
"text": "0.1 mi"
}
},
...
... additional steps of this leg
...
... additional legs of this route
"duration": {
"value": 74384,
"text": "20 hours 40 mins"
},
"distance": {
"value": 2137146,
"text": "1,328 mi"
},
"start_location": {
"lat": 35.4675602,
"lng": -97.5164276
},
"end_location": {
"lat": 34.0522342,
"lng": -118.2436849
},
"start_address": "Oklahoma City, OK, USA",
"end_address": "Los Angeles, CA, USA"
} ],
因此,您可以从响应中提取相关信息。您可以从以下简单的example中受益,将数据绑定到html中的<p>
标记或任何您喜欢的dom元素。希望这会有所帮助。