我有一个通过JSON AJAX请求检索的对象,如下所示:
{
"success":false,
"errors": {
"name":"Name you entered is not valid!",
"emailError":"The email address you entered is not valid"
}
}
现在我需要将errors
属性转换为HTML列表。这就是我在这个阶段使用这些错误的方法:
if (!data.success) { // If fails
if (data.errors.emailError) {
$('#messages').fadeIn(1000).append('<div class="response-output">' + data.errors.emailError + '</div>');
}
}
更新: 我的服务器端代码如下所示:
$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`
if(isset($_POST['your_name'], $_POST['your_email'], $_POST['your_message'])) {
// Sanitize and validate the data passed in
if (preg_match ('/^[A-Z \'.-]{2,60}$/i', $_POST['your_name'])) {
$name = filter_input(INPUT_POST, 'your_name', FILTER_SANITIZE_STRING);
} else {
$errors['name'] = 'Name you entered is not valid!';
}
$email = filter_input(INPUT_POST, 'your_email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$errors['emailError'] = 'The email address you entered is not valid';
}
// if form fields ok
if (empty($errors)) {
// --- my mail
$mail_sent = mail($sendTo, $subject , $emailbody, implode("\r\n", $headers));
if ($mail_sent == true){
// Success massege
$form_data['success'] = true;
$form_data['posted'] = 'Your requirement have been sent. We will get back to you soon.';
}
} else {
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
//Return the data back to form.php
echo json_encode($form_data);
}
但我想在我的#messages
div中创建HTML列表。希望有人可以帮助我。
答案 0 :(得分:1)
当width
为false时,您可以使用.html
循环来迭代.body
对象的属性,并从那里创建所需的for
和{{1元素:
errors
请注意,可以通过使success
属性包含数组而不是对象来改进响应。如何实现这一点将取决于您从AJAX请求生成响应的方式。