2013-08-18 19 views
1

嗨,這裏是我正在做的,這是一個註冊表單,首先我正在做一個檢查,看看用戶名是否可用,如果它是他們繼續進行註冊。 如果用戶名可用,我想給用戶反饋,名稱可用,並且註冊進行,問題是,我做了ajax請求,但是響應一起回來,不是一個,然後是另一個,是在那裏一種方法,我能做到這一點的反應來一個,然後其他的,下面是代碼: *注:PHP和JS文件是外部ajax請求與PHP響應的順序,而不是數組

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';  
} 

?> 

我發現了幾個類似於我的問題,但並不完全無法找到明確的答案,所以我發佈了我的問題,謝謝

回答

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 { 
    ... 
} 
+0

感謝您的回覆,所以我想這是不可能的,因爲(套接字關閉)。 Couse甚至用你建議的方式,我不能先通過'name_available'響應,然後在完成後通過'registration_complete'? –

0

我能得到這個工作的唯一方法是發送第二請求

代碼示例

//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…" 
} 

我希望它可以幫助別人