hi how can i get json from a URL using javascript

advertisements

This question already has an answer here:

  • How to get JSON from URL in Javascript? 3 answers
  • HTTP GET request in JavaScript? 21 answers

I am trying to build a browser extension with key functionality including fetching a text input from html pages and concat it with a URL and fetch json from that concated URL.

I want to know how to fetch json from a URL to a variable using JavaScript.

This is the html script to grab the user inserted text.

<html>
<body>
<input type="text" id="search" name="Name" maxlength="10" class="searchField" autocomplete="off" title="" ><br>
  </p>
</form>
<p align="center">
<button type="button" id="srchbutton" style="background-color:Thistle;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:%"> Search</button>
</p>
<script language="javascript" type="text/javascript" src="thanq.js">
    var button= document.getElementById('srchbutton');
    button.onclick= linkprocess();
    console.log("hi there");
</script>
</body>
</html>

and this is the JavaScript in which I am trying to access the json from URL.

var oldlink='URL';
var newlink;
function linkprocess(links){
    var text= document.getElementById('search');
   newlink=oldlink+text;
   GetJson(newlink);
   console.log(newlink);
}


You can use xmlhttp request in pure javascript to do this. Take a look at this w3 schools article: JSON Http Request

To simplify the code written, you could you jQuerys $.get() or $.ajax() methods once you are comfortable with the mechanism.