如何转换ajax代码以将JSON数据转换为Jquery代码

时间:2016-07-05 08:09:14

标签: javascript jquery ajax

<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>  

我已经编写了如何使用ajax代码获取json数据的代码。现在我想转换此代码以使用jquery获取json数据。另外我想使用我在ajax代码中使用的相同json url。如何使用jquery获取json数据?

1 个答案:

答案 0 :(得分:2)

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(response) {
        $('#name').text(response.name);
        $('#country').text(response.country);
      });
    });

  });
</script>