dongnuo4594 2011-07-13 06:54
浏览 862
已采纳

AJAX请求返回'undefined'

For some reason I always receive undefined if I return the value but if I'm trying to display it in alert I receive the php values.


function getXMLHttp() {
  var xmlHttp

  try {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  } catch(e) {
    //Internet Explorer
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        //Browser does not support AJAX
        return false;
      }
    }
  }

  return xmlHttp;
}

function isUsernameExists() {
  var xmlHttp = getXMLHttp();

  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
    handleResponse(xmlHttp.responseText);
    }
  }

  var str = document.getElementById('username').value.toString();
  xmlHttp.open("GET", "ajax.php?username="+str, true);
  xmlHttp.send(null);

}

Edit:


function handleResponse(response) {
    return response.toString();
}

Thanks,

Guy Dor

  • 写回答

3条回答 默认 最新

  • duanfan8699 2011-07-13 06:58
    关注

    It looks like you are trying to read the return value from this function:

    function isUsernameExists() {
    

    It doesn't have a return statement, so it will always be undefined.

    I'm guessing you expect this return statement to pass the value you want:

    return xmlHttp.responseText.toString();
    

    But that is part of this function:

    xmlHttp.onreadystatechange = function() {
    

    Which is called automatically when the readystatechange event fires, and not by any function call you make.

    Asynchronous JavaScript and XML rarely uses XML but is asynchronous. Anything you want to do with the data fetched needs to be done by the callback function you assign to onreadystatechange. It can call other functions, but it cannot return anything (at least not that will be received anywhere useful).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn