0

我已经按照这个教程学习了如何使用 PHP 和 jQuery 制作联系表格。对于我的理解,这个想法是让 jquery 工作并将 php 作为“备份”。

我按照教程没有任何问题。或者我是这么想的......但最后似乎 jQuery 不起作用。验证时我总是得到一个“闪烁”(页面刷新)。

这是我试图在其中使用它的页面:http: //dccf.site88.net/test/dccf.php

这是PHP:

// Set email variables
$email_to = 'luis_bento@hotmail.com';
$email_subject = 'Message from DCCF site';

// Set required fields
$required_fields = array('fullname','email','comment');

// set error messages
$error_messages = array(
    'fullname' => 'Please enter a Name to proceed.',
    'email' => 'Please enter a valid Email.',
    'comment' => 'Please enter a Message to continue.'
);

// Set form status
$form_complete = FALSE;

// configure validation array
$validation = array();

// check form submittal
if(!empty($_POST)) {
    // Sanitise POST array
    foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));

    // Loop into required fields and make sure they match our needs
    foreach($required_fields as $field) {       

        // the field has been submitted?
        if(!array_key_exists($field, $_POST)) array_push($validation, $field);

        // check there is information in the field?
        if($_POST[$field] == '') array_push($validation, $field);

        // validate the email address supplied
        if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
    }

    // basic validation result
    if(count($validation) == 0) {

        // Prepare our content string
        $email_content = 'New Website Comment: ' . "\n\n";

        // simple email content
        foreach($_POST as $key => $value) {
            if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
        }

        // if validation passed ok then send the email
        mail($email_to, $email_subject, $email_content);

        // Update form switch
        $form_complete = TRUE;
    }
}
function validate_email_address($email = FALSE) {
    return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
   return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>




        <div id="formWrap">
    <h2>If you like our project, have any questions, or would like more information, please send us a message.</h2><!-- end of "Form Message" h2 -->
    <div id="form">
    <?php if($form_complete === FALSE): ?>
    <form action="dccf.php" method="post" id="comments_form">
        <div  class="row">
            <div class="label">Your Name:</div><!-- end of .label -->
            <div class="input">
                <input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /><?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
            <div class="context">e.g. John Smith or Jane Doe</div><!-- end of .context --> 
        </div><!-- end of .row -->

        <div  class="row">
            <div class="label">Your Email:</div><!-- end of .label -->
            <div class="input">
                <input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
            <div class="context">e.g. youremail@somewhere.com</div><!-- end of .context --> 
        </div><!-- end of .row -->

        <div  class="row">
            <div class="label">Your Message:</div><!-- end of .label -->
            <div class="input">
                <textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea><?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
        </div><!-- end of .row -->

        <div class="submit">
            <input type="submit" id="submit" name="submit" value"Send Message" />
        </div><!-- end of .submit -->

        </form>
        <?php else: ?>
        <p class="thanks">Thank you for your Message! We will get back to you as soon as possible.</p>
        <?php endif; ?>
    </div><!-- end of #form -->
</div><!-- end of #formWrap -->

和java脚本:在:

    <script type="text/javascript">
    var nameError = '<?php echo $error_messages['fullname']; ?>';
    var emailError = '<?php echo $error_messages['email']; ?>';
    var commentError = '<?php echo $error_messages['comment']; ?>';
</script>

在validation.js中:

    window.addEvent('domready', function() {
// Get the form
var form = $('comments_form');

//  if the form is found...
if (form) {
    // obtain error fields
    var name = $('fullname');
    var email = $('email');
    var comment = $('comment');

    // Set the default status
    var isValid = true;

    // input error function for the error messages
    var addError = function (field, msg) {
        field.addClass('error'); // Add error class to field
        var error = field.getParent().getElement('span') || new Element('span', {'class': 'error'}); // add error message if not already placed
        error.set('text', msg); // error text msg
        error.inject(field, 'after'); // Insert error message after field
    };

    // detach error function used to delete any error messages and remove the error class
    var removeError = function (field) {
        field.removeClass('error'); // Remove error class from form fields
        var error = field.getParent().getElement('span'); // find any existing error messages

        // destroy if error message
        if (error) {
            error.destroy();
        }
    };

    //  insert submit form event
    form.addEvent('submit', function (e) {
        // Test name length
        if (name.get('value').length === 0) {
            isValid = false;
            addError(name, nameError);
        } else {
            isValid = true;
            removeError(name);
        }

        // check email length
        if (email.get('value').length === 0) {
            isValid = false;
            addError(email, emailError);
        // check email validity
        } else if (!email.get('value').test(/^([a-zA-Z0-9\+_\-]+)(\.[a-zA-Z0-9\+_\-]+)*@([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}$/)) {
            isValid = false;
            addError(email, emailError);
        } else {
            isValid = true;
            removeError(email);
        }

        // check comment length
        if (comment.get('value').length === 0) {
            isValid = false;
            addError(comment, commentError);
        } else {
            isValid = true;                     
            removeError(comment);
        }

        // If form invalid then stop event happening
        if (!isValid) {
            e.stop();
        }
    });
}   
});

谢谢您的帮助!=)

编辑:在控制台上出现了几个错误(在加载页面时,没有提交表单):

  • 视口参数键“width_device-width”无法识别和忽略。dccf.php:8
  • TypeError:“未定义”不是函数(评估“form.addEvent”)validation.js:4
4

1 回答 1

0

由于您的代码存在很多问题,因此我删除了之前的答案。

这是删除了所有错误的 jQuery 等价物,所以它

  1. 如果仅填写了后面的字段之一,则不再允许提交
  2. 没有使用 string.test(regex) 而是使用正确的 regex.test(string)
  3. 在名称字段中使用全名而不是名称
  4. 每次按下提交时重置 isValid

演示

$(function() {
  // Get the form
  var form = $('#comments_form');

  //  if the form is found...
  if (form) {

    // input error function for the error messages
    var addError = function (field, msg) {
        field.addClass('error'); // Add error class to field
        var error = field.parent().find('span') || $('<span>', {'class': 'error'}); // add error message if not already placed
        error.html(msg); // error text msg
        field.after(error); // Insert error message after field
    };

    // detach error function used to delete any error messages and remove the error class
    var removeError = function (field) {
        field.removeClass('error'); // Remove error class from form fields
        var error = field.parent().find('span'); // find any existing error messages

        // destroy if error message
        if (error) {
            error.remove();
        }
    };

    //  insert submit form event
    form.on('submit', function (e) {


        // Set the default status
        var isValid = true;

        // Test name length
        var name = $("#fullname");
        if (name.val().length === 0) {
            isValid = false;
            addError(name, nameError);
        } else {
            removeError(name);
        }

        // check email length
        var email = $("#email");
        var emailVal = email.val();
        if (emailVal.length === 0) {
            isValid = false;
            addError(email, emailError);
        // check email validity
        } else if (!/^([a-zA-Z0-9\+_\-]+)(\.[a-zA-Z0-9\+_\-]+)*@([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}$/.test(emailVal)) {
            isValid = false;
            addError(email, emailError);
        } else {
            removeError(email);
        }

        // check comment length
        var comment = $("#comment");
        console.log(comment.val())
        if (comment.val().length === 0) {
            isValid = false;
            addError(comment, commentError);
        } else {
            removeError(comment);
        }

        // If form invalid then stop event happening
        if (!isValid) {
            e.preventDefault();
        }
    });
  }   
});
于 2013-01-26T10:09:09.617 回答