Grab Text from a File Ajax


/ Published in: JavaScript
Save to your folder(s)

Very basic grab a line of text from a file then display it in an alert box. Uses other functions for loading prepareLinks() and creating the request.


Copy this code and paste it in your HTML
  1. function basicAJAX(file) {//pass a variable into the function
  2. var request = getHTTPObject();
  3. if(request){
  4. request.onreadystatechange = function() {
  5. displayResponse(request);
  6. };
  7. request.open("GET", file, true);//this is where the var is picked up, the location
  8. request.send(null);
  9. }
  10. }
  11. function displayResponse(request) {
  12. if(request.readyState == 4){//waits for the complete before execute.
  13. if(request.status == 200 || request.status == 304){
  14. alert(request.responseText);//this is what happens once complete
  15. //for XML
  16. //var data = request.responseXML;//the while document is now in this variable. Travesrse it using the DOM.
  17. //createInfo(data);//function runs and references the DOM
  18. } else {
  19. alert("Something Broke!");
  20. }
  21. }
  22. }
  23. function prepareLinks(){
  24. if(!document.getElementsByTagName) return false;
  25.  
  26. var allLinks = document.getElementsByTagName("a");
  27. for(i=0;i<allLinks.length;i++){
  28. allLinks[i].onclick = function() {
  29. basicAJAX(this.href);
  30. return false;
  31. }
  32. }
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.