Rahul Rahul - 5 months ago 10
Ajax Question

how to convert ajax code to get JSON data into Jquery code

<html>
<head>
<title>AJAX JSON </title>
<script type="application/javascript">
function load()
{
var url = "http://www.tutorialspoint.com/json/data.json";//use url that have json data
var request;
//XMLHttpRequest Object is Created
if(window.XMLHttpRequest){
request=new XMLHttpRequest();//for Chrome, mozilla etc
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only
}
//XMLHttpRequest Object is Configured
request.onreadystatechange = function(){
if (request.readyState == 4)
{
var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object
document.getElementById("name").innerHTML = jsonObj.name;
document.getElementById("country").innerHTML = jsonObj.country;
}
}
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body>

Name: <span id="name"></span><br/>
Country: <span id="country"></span><br/>
<button type="button" onclick="load()">Load Information</button>
</body>
</html>


i have written the code for how to get json data using ajax code.Now i want to convert this code to get json data using jquery. Also i want to use same json url which i used in ajax code. How to get json data using jquery?

Answer
Name: <span id="name"></span><br/>  
Country: <span id="country"></span><br/>  
<button type="button" id="load">Load Information</button> 
<script type="text/javascript">
  $(document).ready(function() {
    $('#load').click(function() {
      $.get('https://www.tutorialspoint.com/json/data.json', function(r) {
        $('#name').text(r.name);
        $('#country').text(r.country);
      });
    });

  });
</script>