开发者

AJAX responseText not getting anything

开发者 https://www.devze.com 2023-01-08 11:44 出处:网络
I wrote this simple AJAX script: var request; function createRequest(){ request = null; try{ request = new XMLHttpRequest();

I wrote this simple AJAX script:

 var request; 




function createRequest(){ 

 request = null;

 try{
 request = new XMLHttpRequest();

 }catch(failed){
  request = null;

 }

 if(request==null){
  alert("Incompatible Browser");
 }



}



function getProd(form){


 createRequest();


 var w = form.list.selectedIndex;
 var cat = form.list.options[w].text;

 var url = "showProd.do?prodCat=" + cat;

 request.open("GET",url,false开发者_高级运维);

 //Send request to server
 request.onreadyStateChange = updatePage();
 request.send(null);

}

function updatePage(){

 //if(request.readyState == 4){
  //add your code here
  var options = "Bloody Server";
  options = request.responseText;
  //docWrite(options);
  alert(options);
 //}

}

I used firebug to check the response i was getting from server. Its absolutely fine and is of type "text/html".

Problem is it doesn't show up in alert box!


By writing request.onreadyStateChange = updatePage(), you are calling the updatePage function and assigning its return value to onreadyStateChange (which, by the way, must be lowercase)

You need to assign the function itself to onreadystatechange without calling it by removing the ().

For example:

request.onreadystatechange = updatePage;

Note that using a global request variable is a horrible idea; your code cannot send two requests at once.

I highly recommend that you use an existing AJAX framework, such as jQuery's, instead.


umm, you are calling your update function on every state change and all but the last will be before there is any data available, resulting in undesirable results.

You need to update your page when readystate==4

 createRequest();


....

 request.open("GET",url,false);

 //Send request to server
 request.onreadyStateChange = function(){

 if(request.readyState == 4){
  //add your code here
  var options = "Bloody Server";
  options = request.responseText;
  //docWrite(options);
  alert(options);
 }

};
 request.send(null);

....
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号