2016-07-05 37 views
-2
<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 code.Now我想這段代碼轉換使用jQuery獲取JSON數據獲取JSON數據的代碼。此外,我想使用相同的JSON網址,我用阿賈克斯代碼。如何使用jQuery獲取json數據?如何轉換AJAX代碼來獲得JSON數據到jQuery代碼

+0

呃''.ajax'也許? – gcampbell

+0

http://api.jquery.com/jQuery.ajax/ –

回答

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

謝謝..我明白了。 – Rahul

+0

get方法中「r」的含義是什麼? – Rahul

+0

這是來自服務器的響應JSON。我更新了我的答案 –