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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度