在 ajax 响应中返回多个错误证明很麻烦,如果回显多个错误,例如 1&2 变为 12。在数组中返回响应数据的最佳方法是什么?非常感谢任何帮助,在此先感谢。
这是将表单发布到 PHP 验证器的函数
$("document").ready(function() {
$("#btn-signup").click(function() {
var first_name = $("#fname_up").val();
var last_name = $("#lname_up").val();
var vemail = $("#email_up").val();
var password = $("#password_up").val();
var cpassword = $("#cpassword_up").val();
var dataString = 'firstname='+first_name+'&lastname='+last_name+'&email='+vemail+'&password='+password+'&cpassword='+cpassword;
$.ajax({
type: "POST",
url: "-signup.php",
data: dataString,
success: function(response){
if (response == 1) {
console.log("1");
}
if (response == 2) {
console.log("2");
}
if (response == 3) {
console.log("3");
}
if (response == 4) {
console.log("4");
}
if (response == 5) {
console.log("5");
}
if (response == 6) {
console.log("6");
}
if (response == 7) {
console.log("7");
}
if (response == 12) {
console.log("You got to here");
}
}
});
return false;
});
});
这是 PHP 表单验证器。
<?php
session_start();
require_once "database.php";
db_connect();
$errors = array();
// If request is a form submission
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Validation
// Check first_name is non-blank
if(0 === preg_match("/\S+/", $_POST['firstname'])){
echo "1";
}
// Check last_name is non-blank
if(0 === preg_match("/\S+/", $_POST['lastname'])){
echo "2";
}
// Check email is valid (enough)
if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){
echo "3";
}
// Check password is valid
if(0 === preg_match("/.{6,}/", $_POST['password'])){
echo "4";
}
// Check password confirmation_matches
if(0 !== strcmp($_POST['password'], $_POST['cpassword'])){
echo "5";
}
// If no validation errors
if(0 === count($errors)){
// Sanitize first, last, and email
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$cpassword = mysql_real_escape_string($_POST['cpassword']);
// Generate pseudo-random salt
$salt = sha1(microtime() . $_POST['password']);
// Generate password from salt
$password = sha1($salt . $_POST['password']);
// Insert user into the database
$query = "INSERT INTO.......
$result = mysql_query($query);
if(mysql_errno() === 0){
// Registration successful
$user_id = mysql_insert_id();
log_in($user_id);
echo "9";
} else if (preg_match("/^Duplicate.*email.*/// get rid of the two lines beforei", mysql_error())){
echo "10";
}
}
}