我试图同时显示多个错误结果(如果有一个以上的错误结果),而不是逐个显示。让用户一次看到全部错误,以便一次修复。
这是我的代码:在主页
<form id="iform" name="iform" onsubmit="validate(); return false">
<table width="509"><tr>
<td width="114">Name User</td>
<td width="177"><input type="text" name="owner" id="owner"/></td><td id="err1" width="202" style="color:red;"></td></tr><tr>
<td>Email </td><td><input type="email" name="email" id="email"/></td><td id="err2" style="color:red;"></td></tr><tr>
<td>Paypal</td>
<td><input type="email" name="paypal" id="paypal" /></td><td id="err3" style="color:red;"></td></tr><tr>
<td> </td>
<td><input type="submit" value="Submit" /></td></tr>
</table>
</form>
Ajax
$.ajax({
url:'engine.php',
data:{
action:'add_user',
owner:document.iform.owner.value,
email:document.iform.email.value,
paypal:document.iform.paypal.value
},
type:'POST',
success: function(data){
if (data=="er1"){
$("#err2").html("This email is already existed, please try another");
return false;
}
if (data=="er2"){
$("#err3").html("This paypal account is already existed, please try another");
return false;
}
if (data=="ok"){
location.reload();
}
}
});
在PHP中
$owner=$_POST[owner];
$email=$_POST[email];
$paypal=$_POST[paypal];
$ss = $conn->prepare('select email_owner, paypal_owner from tb_owner');
$ss->execute();
$watashi=$ss->fetch();
if ($email==$watashi['email_owner']){
echo"er1";
}
else if ($paypal==$watashi['paypal_owner']){
echo"er2";
}
else{
/* EVEYTHING IS OK ->INSERT TO DATABASE */
if ($stmt->rowCount()){
echo"ok";
}
}
解决方案很简单:[JSON][1]。
在你的PHP中,你应该有这样的东西:
$errors = array();
if($email==$watashi['email_owner']){
$errors[] = "this email is already existed, try another";
}
if($paypal==$watashi['paypal_owner']){
$errors[] = "this paypal is already existed, try another";
}
if(count($errors) > 0){
echo json_encode(array('status' => 'error', 'errors' => $errors));
然后你可以在Javascript中这样阅读:
success: function(data){
var json = $.parseJSON(data);
if(json.status=== 'error'){
$("#err2").html(json.errors[0]);
$("#err3").html(json.errors[1]);
return false;
}
if(json.status==="success"){
location.reload();
}