ajax同步異步回調函數問題

ajax同步:req.open(‘get’,url,false);

實例:

js方法

    var g_success =false;//全局變量

    function getUser(username){

     if("" == username){

         alert("登錄名不能為空!");

         return;

     }

     g_success = false;

     var url = "<%=path%>/basicdata/gyshtyCheckUsername.do?mode=getUser&username="+encodeURI(encodeURI(username));

     if (window.XMLHttpRequest) {

         req = new XMLHttpRequest();

     } elseif (window.ActiveXObject) {

         req = new ActiveXObject("Microsoft.XMLHTTP");

     }

     if (req) {

         req.open('get',url,false);//同步

         req.setRequestHeader("Content-Length",username.length);

          req.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");

          req.send("username="+encodeURI(encodeURI(username)));

         if (req.readyState == 4){

           if (req.status == 200){

               result = req.responseText;

               if('no.' == result){

                  alert("登錄名不存在!");

                  document.getElementById("username").value ="";

                  document.forms[0].username.focus();                

               }else{

                  g_success = true;

               }

           } 

         }

     }

  }

二、後臺服務類

String username = request.getParameter("username");

          Users users = gyshtyService.findUsersByUsername(username);

          String jsonStr="no";

          if (users!=null) {

             jsonStr = users.getUsername();

          }else{

             jsonStr = "no.";

          }

          response.setContentType("text/xml;charset=GBK");

          response.setHeader("Cache-control","no-cache");

          response.getWriter().print(jsonStr);

           returnnull;

 

ajax異步:req.open(‘get’,url,true);

實例:

一、js方法

function getNext(){

if(window.XMLHttpRequest) {

          req = new XMLHttpRequest();

       } elseif(window.ActiveXObject) {

          req = new ActiveXObject("Microsoft.XMLHTTP");

       }

       if(req) {

          var url = “——”;

          req.open("GET",url,true);

          req.onreadystatechange = completeGetNext; //回調函數

          req.send(null);

       }

    }

function completeGetNext(){

       if(req.readyState == 1) {

          document.getElementById("loadspan").innerHTML =

             "<img src='../image/loading.gif' align='absmiddle'>&nbsp;&nbsp;<font color=red>數據加載中,請等待…</font>";

       }

       if(req.readyState == 4) {

          if(req.status == 200) {

             //取到結果之後,開始……

             parseMessageNext();

          }

       }

    }

 

二、後臺服務類

response.setContentType("text/xml;charset=GBK");

          response.setHeader("Cache-control","no-cache");

          String xml = "<?xml version=\"1.0\" encoding=\"GBK\" ?>";

          /*

             與數據庫交互,業務邏輯等

          */

           response.getWriter().write(xml + str);

 

個人總結:在使用異步(true)時可以定義回調函數,在使用同步(false)時回調函數不能另定義一個回調函數名字。個人不知道原因所在,希望大傢告訴一下原因。

備註:以上代碼是開發中已經實現功能的代碼。

 

 

 

 

發佈留言