簡體   English   中英

純 JavaScript REST API 調用

[英]Pure JavaScript REST API call

當我調用函數 CallMe 時,我從服務中得到一個結果,但我的 HTML 元素的文本未定義,因為服務仍在加載數據。 我嘗試異步,等待 Test() 但沒有結果。 我希望這是純 JS。 我做錯了什么?

 CallMe(){
   document.getElementById('testId').InnerHTML = Test();
}

function Test(){
    var request = new XMLHttpRequest(); // Create a request variable and assign a new XMLHttpRequest object to it.
    request.open('GET', 'https://some service'); // Open a new connection, using the GET request on the URL endpoint
    request.send();

    request.onload = async function () {
        var data = await JSON.parse(this.response);
        return data[0][0][0];
      }
}
function CallMe() {
    var request = new XMLHttpRequest(); // Create a request variable and assign a new XMLHttpRequest object to it.
    request.open('GET', 'https://some service'); // Open a new connection, using the GET request on the URL endpoint
    request.send();
    
    request.onload = async function () {
        var data = JSON.parse(this.response);
        document.getElementById('testId').InnerHTML = data // depending on your response targert your desired property.
    }
}

只需執行一種方法,當調用返回響應時,將值分配給您的 testId div

我建議使用 fetch api,而不是使用 XMLHttpRequest 進行 ajax 調用,因為它使用了 Promises,它可以實現更簡單、更清晰的 API,避免回調地獄,並且必須記住 XMLHttpRequest 的復雜 API。 (參考: https : //developers.google.com/web/updates/2015/03/introduction-to-fetch )。

使用 fetch api,純 js 中的代碼將如下所示。

fetch('https://some service')
.then( res => res.json() )
.then(response => {
    document.getElementById('testId').innerHTML = data[0][0][0];
}) 
.catch(error => console.error('Error:', error));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM