简体   繁体   中英

Javascript : returning value from my ajax function

function ajaxFunction(id){
  var ajaxRequest;
  var response;
      try{
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = new XMLHttpRequest();
      } catch (e){
      // Internet Explorer Browsers
      try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
      try{
      ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e){
      alert("Ajax Failed");
      return false;
    }
  }
}
ajaxRequest.onreadystatechange = function(){
  if(ajaxRequest.readyState == 4){
    response = ajaxRequest.responseText;
  }
}
ajaxRequest.open("GET", "http://priest/getpic.php?id="+id, true);
ajaxRequest.send(null);
return response;

}

function lightbox(id) {
var image;
var imageArr;
document.write(image);

image = ajaxFunction(id);
imageArr = image.split('|');

imageSrc = imageArr[0];
imageWidth = imageArr[1];
imageHeight = imageArr[2];

getElementById('lightbox').visibility=visible;
getElementById('lightboximg').src=imageSrc;

if(imageWidth > 700) {getElementById('lightboximg').width=700;}
if(imageHeight > 500) {getElemetnById('lightboximg').height=500;}


}

The problem I'm having is where my code calls the ajaxFunction() into the image variable the ajaxFunction() isn't returning anything into the variable, causing me to get the following error.

Uncaught TypeError: Cannot call method 'split' of undefined lightbox (anonymous function)

Any Help would be greatly Appreciated.

AJAX stands for Asynchronous JavaScript and XML . The key part here is really the Asynchronous part. What it means is that when you send a request to the server for information, the browser fetches the information in the background without interfering with the display and behavior of the existing page. Because of this, callbacks are huge when it comes to AJAX - you don't know if your server is going to take 500ms or 3s to return the value, so all you can really do is send the request and say "when you're done, I want you to do this ". In your current code your server will very rarely have had time to return whatever getpic.php does before you try returning the value to the function. You just have to modify your code so that ajaxFunction can accept a second argument that is a function callback that is then run within the onreadystatechange part of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM