2013-03-09 43 views
0

儘管我在凌晨2點喜歡奧祕,但我認爲最好提問。Javascript ajax只有在添加虛擬線路時纔會醒來

我使用onblur事件來傳遞「this」(例如this = input.password)。由於某種原因, handleServerResponse什麼也不做,除非我添加一行來呢,一起來看看:

普通AJAX功能:

function ajaxFunction(obj) 
{ 
    var button = document.getElementById("submit"); 
    button.disabled = true; 
    button.setAttribute("class", "test"); 
    var getdate = new Date(); //Used to prevent caching during ajax call 
    xmlhttp.onreadystatechange = handleServerResponse(obj); 

    if(xmlhttp) 
    { 
    //var input = document.forms["signup_form"].getElementsByTagName("input"); 
    xmlhttp.open("POST","register_ajax.php",true); 

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 

    xmlhttp.send(obj.name +"="+ obj.value); 
    }; 
} 

handleServerResponse - 不工作

function handleServerResponse(obj) 
{ 
    if (xmlhttp.readyState == 4) 
    { 
     if(xmlhttp.status == 200) 
    { 
      obj.value=xmlhttp.responseText; //Update the HTML Form element 
    } 
    else 
    { 
     alert("Error during AJAX call. Please try again"); 
    } 
    } 
} 

handleServerResponse - 工作的

function handleServerResponse(obj) 
{ 
    alert(xmlhttp.responseText); 
    if (xmlhttp.readyState == 4) 
    { 
     if(xmlhttp.status == 200) 
    { 
      obj.value=xmlhttp.responseText; //Update the HTML Form element 
    } 
    else 
    { 
     alert("Error during AJAX call. Please try again"); 
    } 
    } 
} 

回答

0

在此行中

xmlhttp.onreadystatechange = handleServerResponse(obj); 

您呼叫handleServerResponse而非readyState的變化處理程序設置。您必須指定一個函數xmlhttp.onreadystatechange您正在做的是分配handleServerResponse(obj)的回報。嘗試

xmlhttp.onreadystatechange = function(){ 
            handleServerResponse(obj); 
           }; 

也是爲什麼第二個成功是因爲警報塊執行一個Ajax調用完成後都取得了檢查前的原因。

+0

忘記JavaScript的行爲不同。謝謝,我終於可以入睡了。 – 2013-03-09 00:15:33

3

您的「作品」意外地工作,它並不實際工作。

會發生什麼事是:

  1. XMLHTTP請求被髮送(答覆會在以後的時間)。
  2. 您立即嘗試檢查readyState,這不是4還因爲尚未準備好!

在這種情況發生另一種情況下:

  1. XMLHTTP請求被髮送(回覆會在以後的時間)。
  2. 您使用alert來阻止瀏覽器。當警報打開時,AJAX請求返回。
  3. 您立即檢查readyState,現在它4

如果您關閉了alert速度不夠快它會再次突破。

處理AJAX(以及通常的異步)的正確方法是使用事件偵聽器。

xmlhttprequest.addEventListener("onreadystatechange", function (event) { 
    if (xmlhttprequest.readyState === 4) { 
     // handle reply 
    } 
}); 
相關問題