Enjoy an ad free experience by logging in. Not a member yet? Register.
|
|
Results 1 to 1 of 1
-
11-02-2015, 02:43 AM #1Regular Coder
- Join Date
- Oct 2002
- Posts
- 208
- Thanks
- 3
- Thanked 0 Times in 0 Posts
Process AJAX calls & responses via external java file?
I've been trying to get up to speed on using AJAX. But there's one thing in particular that I don't understand. Every tutorial I've seen is hard coded to update specific fields on a given page. My current code based on one such tutorial is below. What I'd like to do is to put the required code in an external file and link it in to any pages that need it. I'd like to make this reusable (I've got a few different sites that I keep on one server which means they will all share the same java file).
Code:<!DOCTYPE html> <html> <head> <meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type"> <script type = "application/javascript"> function loadJSON(){ var data_file = "http://www.doni.com/cr5/AjaxTest.php"; var http_request = new XMLHttpRequest(); try{ // Opera 8.0+, Firefox, Chrome, Safari http_request = new XMLHttpRequest(); }catch (e){ // Internet Explorer Browsers try{ http_request = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try{ http_request = new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } http_request.onreadystatechange = function(){ if (http_request.readyState == 4 ){ // Javascript function JSON.parse to parse JSON data var jsonObj = JSON.parse(http_request.responseText); return jsonObj; // jsonObj variable now contains the data structure and can // be accessed as jsonObj.name and jsonObj.country. //document.getElementById("Name").innerHTML = jsonObj.name; //document.getElementById("Country").innerHTML = jsonObj.country; } } http_request.open("GET", data_file, true); http_request.send(); } function getData(){ jsonObj = loadJSON(); document.getElementById("Name").innerHTML = jsonObj.name; document.getElementById("Country").innerHTML = jsonObj.country; } </script> <title>tutorialspoint.com JSON</title> </head> <body> <h1>Cricketer Details</h1> <table class = "src"> <tr><th>Name</th><th>Country</th></tr> <tr><td><div id = "Name">Sachin</div></td> <td><div id = "Country">India</div></td></tr> </table> <div class = "central"> <button type = "button" onclick = "getData()">Update Details </button> </div> </body> </html>Last edited by doni; 11-02-2015 at 02:47 AM.



Reply With Quote
