gpt4 book ai didi

php - 带有 php 响应的 ajax 请求按顺序,而不是在数组中

转载 作者:行者123 更新时间:2023-11-29 00:27:28 25 4
gpt4 key购买 nike

大家好,这是我要做的,这是一张注册表,首先我要检查用户名是否可用,如果可用,他们会继续注册。如果用户名可用,我想给用户反馈,名称可用并且已继续注册,问题是,我执行了 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';
}

?>

我发现有几个问题与我的相似,但不完全相同,找不到明确的答案,所以我发布了我的问题,谢谢

最佳答案

您不能按步骤处理数据(至少不能以这种方式),因为 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 {
...
}

关于php - 带有 php 响应的 ajax 请求按顺序,而不是在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18302039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com