在阅读了几篇教程之后,我仍然难以将我的PHP与我的Ajax方法链接起来。有没有办法通过我的$errors[]
将PHP文件中的变量function(data)
放入我的HTML页面?
提前谢谢!
这是我在PHP中的代码:
<?php
if(!empty($_POST)){
$errors = array();
require_once 'inc/db.php';
function str_random($length){
$alphabet ="0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN";
return substr(str_shuffle(str_repeat($alphabet, $length)), 0, $length);}
if(empty($_POST['username']) || !preg_match('/^[a-zA-Z0-9_]+$/', $_POST['username'])){
$errors['username'] = "Votre pseudo n'est pas valide (alphanumérique)";
} else {
$req = $pdo->prepare('SELECT id FROM users WHERE username = ?');
$req->execute([$_POST['username']]);
$user = $req->fetch();
if($user){
$errors['username'] = 'Ce pseudo est déjà pris';
}
}
if(empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$errors['email'] = "Votre email n'est pas valide";
} else {
$req = $pdo->prepare('SELECT id FROM users WHERE email = ?');
$req->execute([$_POST['email']]);
$user = $req->fetch();
if($user){
$errors['email'] = 'Cet email est déjà utilisé pour un autre compte';
}
}
if(empty($_POST['password']) || $_POST['password'] != $_POST['password_confirm']){
$errors['password'] = "Vous devez rentrer un mot de passe valide";
}
if(empty($errors)){
$req = $pdo->prepare("INSERT INTO users SET username = ?, password = ?, email = ?, confirmation_token = ?");
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$token = str_random(60);
$req->execute([$_POST['username'], $password, $_POST['email'], $token]);
$user_id = $pdo->lastInsertId();
mail($_POST['email'], 'Confirmation de votre compte', "Afin de valider votre compte merci de cliquer sur ce lien\n\nhttp://localhost/Type&GoSite/confirm?id=$user_id&token=$token");
$_SESSION['flash']['success'] = 'Un email de confirmation vous a été envoyé pour valider votre compte';
header('Location: login.php');
exit();
}
}
?>
<?php if(!empty($errors)){
header('Content-Type: application/json; Charset=utf-8');
echo json_encode($errors);
exit();}?>
<?php if(!empty($errors)): ?>
<div class="flash2">
<h3>Vous n'avez pas rempli le formulaire correctement</h3>
<ul>
<?php foreach($errors as $error): ?>
<li><?= $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
以下是我的HTML代码:
<div class="container">
<br><br><br>
<h1>S'inscrire</h1>
<div id="resultat"></div>
<form action="" method="POST">
<div class="form-group">
<label for="">Pseudo</label>
<input type="text" id="username" name="username" class="form-control"/>
</div>
<div class="form-group">
<label for="">Email</label>
<input type="text" id="email" name="email" class="form-control"/>
</div>
<div class="form-group">
<label for="">Mot de passe</label>
<input type="password" id="password" name="password" class="form-control"/>
</div>
<div class="form-group">
<label for="">Confirmez votre mot de passe</label>
<input type="password" id="password_confirm" name="password_confirm" class="form-control"/>
</div>
<br>
<button type="submit" id="submit" class="btn btn-primary">M'inscrire</button>
</form>
</div>
这是我的JS(我正在使用jQuery 1.7.2):
$(document).ready(function(){
$("#submit").click(function(e){ e.preventDefault();
$.post('register.php', {
login : $("#username").val(),
password : $("#password").val(),
password_confirm : $("#password_confirm").val(),
email : $("#email").val()
},
function (data) {
if (data && data.length > 0) {
// show errors in your HTML somewhere
$("#resultat").html("voici les erreurs");
} else {
$("#resultat").html("<p>Un email de confirmation vous a été envoyé pour valider votre compte");
}
},
'JSON'
);
});
});
答案 0 :(得分:0)
Structured data is typically transferred in JSON form.
Therefore when there are errors, convert them to JSON in PHP and send them to the client. Don't forget to set the correct Content-Type
header:
if(!empty($errors)){
header('Content-Type: application/json; Charset=utf-8');
echo json_encode($errors);
exit();
}
On the receiving end the $errors
array will arrive and jQuery will helpfully decode the JSON for you, turning it into a regular JS array:
$.post('register.php', {
login : $("#username").val(),
password : $("#password").val(),
password_confirm : $("#password_confirm").val(),
email : $("#email").val()
}).done(function (errors) {
if (errors && errors.length > 0) {
// show errors in your HTML somewhere
$("#resultat").html("...");
} else {
$("#resultat").html("<p>Un email de confirmation vous a été envoyé pour valider votre compte");
}
});