ajax请求与php响应按顺序,而不是在数组中

时间:2013-08-18 17:51:52

标签: php mysql ajax jquery

嗨,大家好,我正在尝试做的,这是一个注册表格,首先我正在检查用户名是否可用,如果是,他们继续注册。 如果用户名可用,我想给用户反馈,该名称是可用的,并且它继续注册,问题是,我做了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';    
}

?> 

我发现了一些与我的相似的问题,但并不完全也找不到明确的答案,所以我发布了我的问题,谢谢

2 个答案:

答案 0 :(得分:1)

你不能按步骤处理数据(至少不是以这种方式处理),因为只有当你的php脚本完成工作(套接字关闭)时,JQuery才会启动你的功能。

使用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 {
    ...
}

答案 1 :(得分: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…"
}

我希望它有助于某人