0

午前2時の謎が大好きなのと同じくらい、聞いてみるのが一番だと思います。

onblurイベントを使用して「this」を渡します(例:this = input.password)。何らかの理由で、handleServerResponseに行を追加しない限り、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");
    }
    }
}
4

2 に答える 2

3

あなたの「作品」がたまたまうまくいき、実際にはうまくいきません。

何が起こるか:

  1. xmlhttp リクエストが送信されます (返信は後で返されます)。
  2. すぐに check を試しますreadyStateが、4まだ準備ができていないため、まだ実行されていません。

それ以外の場合は、次のようになります。

  1. xmlhttp リクエストが送信されます (返信は後で返されます)。
  2. を使用してブラウザをブロックしalertます。アラートが開いている間、AJAX リクエストが返されます。
  3. すぐに確認するreadyStateと、今は です 4

alert に閉めるとまた壊れます。

AJAX (および一般的な非同期性) を処理する適切な方法は、イベント リスナーを使用することです。

xmlhttprequest.addEventListener("onreadystatechange", function (event) {
    if (xmlhttprequest.readyState === 4) {
        // handle reply
    }
});
于 2013-03-09T00:10:32.870 に答える
0

この行で

xmlhttp.onreadystatechange  = handleServerResponse(obj);

handleServerResponseon readystate 変更ハンドラを設定するのではなく、呼び出しています。あなたがしていることに関数を割り当てるxmlhttp.onreadystatechange必要があるのは、 の戻り値を割り当てることですhandleServerResponse(obj)。試す

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

また、2 番目が成功した理由は、アラートが実行をブロックし、チェックが行われる前に ajax 呼び出しが終了したためです。

于 2013-03-09T00:11:20.073 に答える