简体   繁体   中英

Passing DB contents from XHTTP request

I have an xhttp GET request to fetch the items in my db using its api gateway url. The request works fine as I can see my db's contents which are in string (key:value pairs) from the browser's dev console. Where I'm drawing a blank in is how to pass the db's contents to another function that parses it into javascript objects.

Fetch request code

function fetch(){
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
  };
  xhttp.open("GET", "<mygatewayapi_url>", true);
  xhttp.send();
}

Code for parsing db contents into javascript object

function displayObj(dataStr){
    var obj = JSON.parse(dataStr);
    var html = "";
    var item =;
    //var keys = Object.keys(obj);
    //var last = keys[item.length - 1];

    for (item in obj){
        html += '<li>' + item + ' ' + obj[item] + </li>';
        /*if (last === true)
            html += '<li>' + item + ' ' + obj[item] + </li>' + "<br>";*/
    }
    return '<li>'+html+'</li>';

You may handle the result in the xhttp.onreadystatechange callback:

 function fetch(){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var result = displayObj(this.responseText); console.log("result: \n", result); document.getElementById("demo").innerHTML = result; } }; xhttp.open("GET", "https://api.github.com/emojis", true); xhttp.send(); } function displayObj(dataStr){ var obj = JSON.parse(dataStr); var html = ""; for (var item in obj){ html += '<li>' + item + ' ' + obj[item] + '</li>'; } return '<ul>'+html+'</ul>'; } fetch();
 <div id="demo"></div>

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