1

I'm new to javascript. I have a php file that lists all the files in a directory. I want to call that file and get the json array that it echos using only javascript. I know jquery can do it... but this is the only thing I need to do. Its not worth learning jquery for it nor do I want to bloat my page with a library I'm only going to use for this one thing.

3
  • have a look at AJAX - btw, you get use google apis for all sorts of javascript libraries: many sites use them so jquery lib is likely to be already cached by the browser so no extra load - i would really recommend using one of the frameworks out there Commented Apr 14, 2012 at 0:15
  • I'd argue it's still worth using jQuery. It's not just shorter code you get, but more stable code as well. If you host the jquery.min.js file on your own server or a CDN, the time it takes to load it is negligible. Commented Apr 14, 2012 at 0:15
  • 1
    dealing with "pure" ajax is not a simple thing for a begginer - while working with prepared libraries such as jQuery is extremely easy - therefore, you better spend 2 minutes in order to get into it with jquery instead of trying to work directly with AJAX (which is not fully cross platform - a problem that working with jQuery or other libraries solves) Commented Apr 14, 2012 at 0:23

1 Answer 1

2

I would say just use jquery as handling all different browsers for AJAX is a pain and I am sure you will use it in the long run for other things too.

If you really want to do this here is an example of a native js request:

function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}

you would use it like this:

var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
 if (mygetrequest.readyState==4){
  if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
   var jsondata=eval("("+mygetrequest.responseText+")") //retrieve result as an JavaScript object
   var rssentries=jsondata.items
  }
  else{
   alert("An error has occured making the request")
  }
 }
}

mygetrequest.open("GET", "mypage.php", true)
mygetrequest.send(null)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.