1

こんにちは皆さん、これが私がやろうとしていることです。これは登録フォームです。最初に、ユーザー名が利用可能かどうかを確認しています。利用可能であれば、登録を進めます。ユーザー名が利用可能な場合、名前が利用可能であり、登録が続行されていることをユーザーにフィードバックしたかったのですが、問題は、私は ajax リクエストを実行しましたが、応答が 1 つではなく一緒に戻ってきて、別のものがあるかどうかです。応答が次から次へと来るようにする方法を以下に示します:

JSファイル

$.ajax({
    url: "register.php",
    type: "POST",
    data: ({username: nameToCheck, password: userPass, email: userEmail}),
    async: true,
    beforeSend: ajaxStartName,
    success: nameVerify,
    error: ajaxErrorName,
    complete: function() {
        //do something          
    }
});

function nameVerify(data){
    console.log('ajax data: '+data); // this gives both responses, not one then the other

    if(data == 'nameAvailable'){
        //user feedback, "name is available, proceeding with registration"
    }
    else if(data == 'registrationComplete'){
        //user feedback, "registration is complete thank you"
    {
    else if(data == 'nameInUse'){
        //user feedback, "name is in use, please select another…"
    }
}

phpファイル

<?php
// the connection and db selection here
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];

if($total == 1){
echo 'nameInUse';
disconnectDb();
die();
 }
 else{  
echo 'nameAvailable';
 register(); //proceed with registration here
 }

 function register(){
 $password= $_POST['password'];//and all other details would be gathered here and sent
 //registration happens here, then if successful
//i placed a for loop here, to simulate the time it would take for reg process, to no avail
//the echoes always go at same time, is there a way around this?
echo 'registrationComplete';    
}

?> 

私に似たいくつかの質問を見つけましたが、正確ではなく、明確な答えを見つけることができなかったので、質問を投稿します、ありがとう

4

2 に答える 2

1

JQuery は、php スクリプトが作業を終了したとき (ソケットを閉じたとき) にのみ関数を起動するため、段階的にデータを処理することはできません (少なくともこの方法ではできません)。

jsonを使用する

$res - array('name_available' => false, 'registration_complete' => false);
... some code ...
if (...) {
    ...
} else {
    $res['name_available'] = true;
    ...
    if (...) {
        $res['registration_complete'] = true;
    }
}
...
echo json_encode($res);

次にnameVerifyで

data = $.parseJSON(data);
if (data['name_available']) {
    ...
    if (data['registration_complete']) {
        ...
    }
} else {
    ...
}
于 2013-08-18T18:03:52.937 に答える
0

これを機能させることができた唯一の方法は、2番目のリクエストを送信することでした

コードサンプル

//first request
function nameVerify(data){
console.log('ajax data: '+data); // this gives both responses, not one then the other

if(data == 'nameAvailable'){
    //user feedback, "name is available, proceeding with registration"
    *** here after getting the first response, i send a 2nd request,and place the handlers only 'sharing' the error msgs
    confirmation(); //second request
}
else if(data == 'registrationComplete'){
    //user feedback, "registration is complete thank you"
{
else if(data == 'nameInUse'){
    //user feedback, "name is in use, please select another…"
}

それが誰かに役立つことを願っています

于 2013-08-19T04:26:35.287 に答える