简体   繁体   中英

Pure JavaScript REST API call

When I call function CallMe, I get a result from service but my HTML element has text undefined, because of service is still loading data. I try async, await on Test() but no results. I want this to be pure JS. What I do wrong?

 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.
    }
}

just do one method and when the call returns a response assign the value to your testId div

Rather than using XMLHttpRequest to make ajax call I recommend using fetch api as it uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest. (ref: https://developers.google.com/web/updates/2015/03/introduction-to-fetch ).

Using fetch api the your code in pure js will look like below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM