1

大家好,这是我正在尝试做的事情,这是一个注册表单,首先我正在检查用户名是否可用,如果是,他们继续进行注册。如果用户名可用,我想给用户反馈,该名称可用并继续注册,问题是,我发出 ajax 请求,但响应一起返回,而不是一个,然后另一个,是否有我可以这样做,以便一个接一个地响应,下面是代码: *注意:php 和 js 文件都是外部的

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);

然后在名称中验证

data = $.parseJSON(data);
if (data['name_available']) {
    ...
    if (data['registration_complete']) {
        ...
    }
} else {
    ...
}
于 2013-08-18T18:03:52.937 回答
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…"
}

我希望它可以帮助某人

于 2013-08-19T04:26:35.287 回答