doujian1050 2014-01-09 06:37
浏览 464
已采纳

如何在javascript ajax中返回bool(true或false)?

I have tried with this code. But it is not working. I just need to return state of bool value. But always this returns true.

function nic_is_exist(){

  var state = true;
  var nic = document.getElementById("tbNic").value;
  var xmlhttp;
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
  }else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  } 
  xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState == 1){
      document.getElementById("spNic").innerHTML="<img src='../Style/images/loarding.gif' />";  
    }     
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      document.getElementById("spNic").innerHTML="";
      var str = xmlhttp.responseText;
      alert(str+2);
      if( str != "1"){
        alert("if");
        fill_form(str);
        checkNull();
        state = true;   
      }else{
        alert("else");
        state = false;
      }       
    }     
  }
  xmlhttp.open("POST","rpoRegister_PHP.php?a="+nic,true);
  xmlhttp.send();
  return state;
}
  • 写回答

3条回答 默认 最新

  • duanqianwei2485 2014-01-09 06:49
    关注

    AJAX is asynchronous. If you need to do something based on the TRUE/FALSE then you need to put it within your if (xmlhttp.readyState==4 && xmlhttp.status==200) block. Or replace your state = true; and state = false; code with a function call.

    Example:

    if( str != "1"){
        alert("if");
        fill_form(str);
        checkNull();
        doSuccessCode(); 
      }else{
        alert("else");
        doFailCode();
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码