Search code examples
ajaxaframewebvr

Aframe: Binding Async data within Aframe using API response


I am trying to find out if we can integrate an API response within Aframe scene. For example, I want to get the information about an entity object when I move my cursor over it. I know we can have maintained these static data with an a-text, but I am looking for AJAX based integration so that I can add/edit data from the backend.

Please advise.


Solution

  • You could use a custom component, which will grab the text and use it as an <a-text> value. Execute the AJAX call inside an event listener (like a click, or any other one):

    AFRAME.registerComponent("foo", {
      init: function() {
        let self = this.el
        this.el.addEventListener("click", (e)=>{
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              self.children[0].setAttribute("value", this.responseText;
            }
          };
          xhttp.open("GET", "ajax_info.txt", true);
          xhttp.send();
        })
      }
    })
    

    In a setup like this:

    <a-entity foo>
      <a-text></a-text>
    </a-entity>
    

    Something like this, exept with the ajax call, i took the ajax code from w3schools.