Wasteland Wasteland - 3 months ago 15
JSON Question

ReactJS - get json object data from an URL

How do I get data from an URL into ReactJS.

The url is of the following type:
http://www.domain.com/api/json/x/a/search.php?s=category

which, if typed in a browser, will display a json object.

How do I load it to ReactJS.

To start with, I started by:

const dUrl = "http://www.the....";

console.log(dUrl);


but obviously it displays the url not the content (which, I will be able to filter - it's just this initial step of loading it into an object that I don't know)

Edit: I'd rather not use jQuery.

Answer

You will need to use AJAX for that. This is easy using jQuery.

const dUrl = "http://www.the....";

$.ajax(
   {
     url: dUrl, 
     success: function(result){
         console.log(result);
     }
   }
);

You will need to add/import jQuery to make it work.

If you don't want to add ajax then:

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

refer this for more information about AJAX

Comments