-1

我想在地圖 api的控制檯中打印狀態和其他變量。 我創建的XHR對象包含變量中的數據,但是當我打印 xhr.status時,它表示0。但是在控制檯中當我打開XHR對象時,狀態爲 200. 我完全想要打印從maps API返回的所有數據。我甚至啓用了CORS請求 。如何在google頁面上打印來自Google maps方向api的JSON數據

<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

那麼從代碼我很驚訝,你甚至可以稱之爲你的'console.log()' - 它在函數範圍之外... –

回答

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對象包含summarylegs陣列性能如下:

"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": "[email protected]" 
     }, 
     "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中受益,以便將數據綁定到<p>標記或您在html中喜歡的任何dom元素。希望這可以幫助。

+0

謝謝。現在我該如何獲得從JSON響應到我的html文件的確切方向。另外如何在HTML中打印響應 –