1

我知道我以前发过这个,但是我在累了凌晨 2 点的时候发了另一个。这个我能很快回复,我想把这个整理一下,我一发布就删除另一个。

好的,所以标题可能有点令人困惑,但请阅读此内容,然后看看它是否更有意义。

我下载了一个 HTML5 网站模板,它带有一个用于表单操作的联系 php 表单。

这是表单的 HTML:

<form id="contact-form" action="bat/MailHandler.php">
    <div class="success">
         Contact form submitted! <strong>We have received your email and will be with you within 24 hours.</strong>
    </div>
    <fieldset>
        <div>
            <label class="topic">
                <select style="width:370px;" name="topic">
                    <option value="General">General</option>
                    <option value="Development">Development</option>
                    <option value="Graphics">Graphics Design</option>
                    <option value="Video">Video Editing</option>
                </select>
            </label>
        </div>
        <div>
            <label class="name">
            <input type="text" value="Your name">
            <br>
            <span class="error">*This is not a valid name.</span><span class="empty">*This field is required.</span></label>
        </div>
        <div>
            <label class="phone">
            <input type="tel" value="Telephone (Please include country code)">
            <br>
            <span class="error">*This is not a valid phone number.</span><span class="empty">*This field is required.</span></label>
        </div>
        <div>
            <label class="email">
            <input type="email" value="Email">
            <br>
            <span class="error">*This is not a valid email address.</span><span class="empty">*This field is required.</span></label>
        </div>
        <div>
            <label class="message">
            <textarea>Message</textarea>
            <br>
            <span class="error">*The message is too short.</span><span class="empty">*This field is required.</span></label>
        </div>
        <div class="buttons-wrapper">
            <a class="btn btn-1" data-type="reset">Clear</a><a class="btn btn-1" data-type="submit">Send</a>
        </div>
    </fieldset>
</form>

MailHandler.php 看起来像这样:

<?php

    // Database connect
    $db_host        = 'localhost';
    $db_user        = 'redjaxco';
    $db_pass        = 'CORRECT PASSWORD';
    $db_database            = 'redjaxco_website'; 

    $link = mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

    mysql_select_db($db_database,$link);
    mysql_query("SET names UTF8");

    $owner_email = "contact@red-jax.com";

    $headers = 'From:' . $_POST["email"];
    $subject = 'Online Form: '. $_POST["name"];
    $messageBody = "";

    if($_POST['name']!='nope'){
        $messageBody .= '<p>Visitor: ' . $_POST["name"] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
    }
    if($_POST['email']!='nope'){
        $messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
    }else{
        $headers = '';
    }
    if($_POST['phone']!='nope'){        
        $messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
    }
    if($_POST['message']!='nope'){
        $messageBody .= '<p>Message: ' . $_POST['message'] . '</p>' . "\n";
    }

    if($_POST["stripHTML"] == 'true'){
        $messageBody = strip_tags($messageBody);
    }

    try{
        if(!mail($owner_email, $subject, $messageBody, $headers))
        {
            throw new Exception('mail failed');
        }
        else
        {
                            // ignore the SQL thing... It doesn't yet work
            $sql = mysql_query("INSERT INTO customers (
                name,email,telephone
            ) VALUES (
                '{$_POST['name']}',
                '{$_POST['email']}',
                '{$_POST['telephone']}',
            )");

            if (!$sql)
            {
                throw new Exception('mail failed');
            }

            echo 'mail sent';
        }
    }catch(Exception $e){
        echo $e->getMessage() ."\n";
    }
?>

MailHandler 由名为“forms.js”的 javascript 文件驱动。

Forms.js:

//forms
;(function($){
    $.fn.forms=function(o){
        return this.each(function(){
            var th=$(this)
                ,_=th.data('forms')||{
                    errorCl:'error',
                    emptyCl:'empty',
                    invalidCl:'invalid',
                    notRequiredCl:'notRequired',
                    successCl:'success',
                    successShow:'4000',
                    mailHandlerURL:'bat/MailHandler.php',
                    ownerEmail:'support@template-help.com',
                    stripHTML:true,
                    smtpMailServer:'localhost',
                    targets:'input,textarea,select',
                    controls:'a[data-type=reset],a[data-type=submit]',
                    validate:true,
                    rx:{
                        ".topic":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:select'  },
                                                    ".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                        ".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                        ".email":{rx:/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,target:'input'},
                        ".phone":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},
                        ".fax":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},
                        ".message":{rx:/.{20}/,target:'textarea'}
                    },
                    preFu:function(){
                        _.labels.each(function(){
                            var label=$(this),
                                inp=$(_.targets,this),
                                defVal=inp.val(),
                                trueVal=(function(){
                                            var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html()
                                            return defVal==''?defVal:tmp
                                        })()
                            trueVal!=defVal
                                &&inp.val(defVal=trueVal||defVal)
                            label.data({defVal:defVal})                             
                            inp
                                .bind('focus',function(){
                                    inp.val()==defVal
                                        &&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl))
                                })
                                .bind('blur',function(){
                                    _.validateFu(label)
                                    if(_.isEmpty(label))
                                        inp.val(defVal)
                                        ,_.hideErrorFu(label.removeClass(_.invalidCl))                                          
                                })
                                .bind('keyup',function(){
                                    label.hasClass(_.invalidCl)
                                        &&_.validateFu(label)
                                })
                            label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide()
                        })
                        _.success=$('.'+_.successCl,_.form).hide()
                    },
                    isRequired:function(el){                            
                        return !el.hasClass(_.notRequiredCl)
                    },
                    isValid:function(el){                           
                        var ret=true
                        $.each(_.rx,function(k,d){
                            if(el.is(k))
                                ret=d.rx.test(el.find(d.target).val())                                      
                        })
                        return ret                          
                    },
                    isEmpty:function(el){
                        var tmp
                        return (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal')
                    },
                    validateFu:function(el){                            
                        el.each(function(){
                            var th=$(this)
                                ,req=_.isRequired(th)
                                ,empty=_.isEmpty(th)
                                ,valid=_.isValid(th)                                

                            if(empty&&req)
                                _.showEmptyFu(th.addClass(_.invalidCl))
                            else
                                _.hideEmptyFu(th.removeClass(_.invalidCl))

                            if(!empty)
                                if(valid)
                                    _.hideErrorFu(th.removeClass(_.invalidCl))
                                else
                                    _.showErrorFu(th.addClass(_.invalidCl))                             
                        })
                    },
                    getValFromLabel:function(label){
                        var val=$('input,textarea',label).val()
                            ,defVal=label.data('defVal')                                
                        return label.length?val==defVal?'nope':val:'nope'
                    }
                    ,submitFu:function(){
                        _.validateFu(_.labels)                          
                        if(!_.form.has('.'+_.invalidCl).length)
                            $.ajax({
                                type: "POST",
                                url:_.mailHandlerURL,
                                data:{
topic:_.getValFromLabel($('.topic',_.form)),
                                    name:_.getValFromLabel($('.name',_.form)),
                                    email:_.getValFromLabel($('.email',_.form)),
                                    phone:_.getValFromLabel($('.phone',_.form)),
                                    fax:_.getValFromLabel($('.fax',_.form)),
                                    state:_.getValFromLabel($('.state',_.form)),
                                    message:_.getValFromLabel($('.message',_.form)),
                                    owner_email:_.ownerEmail,
                                    stripHTML:_.stripHTML
                                },
                                success: function(){
                                    _.showFu()
                                }
                            })          
                    },
                    showFu:function(){
                        _.success.slideDown(function(){
                            setTimeout(function(){
                                _.success.slideUp()
                                _.form.trigger('reset')
                            },_.successShow)
                        })
                    },
                    controlsFu:function(){
                        $(_.controls,_.form).each(function(){
                            var th=$(this)
                            th
                                .bind('click',function(){
                                    _.form.trigger(th.data('type'))
                                    return false
                                })
                        })
                    },
                    showErrorFu:function(label){
                        label.find('.'+_.errorCl).slideDown()
                    },
                    hideErrorFu:function(label){
                        label.find('.'+_.errorCl).slideUp()
                    },
                    showEmptyFu:function(label){
                        label.find('.'+_.emptyCl).slideDown()
                        _.hideErrorFu(label)
                    },
                    hideEmptyFu:function(label){
                        label.find('.'+_.emptyCl).slideUp()
                    },
                    init:function(){
                        _.form=_.me                     
                        _.labels=$('label',_.form)

                        _.preFu()

                        _.controlsFu()

                        _.form
                            .bind('submit',function(){
                                if(_.validate)
                                    _.submitFu()
                                else
                                    _.form[0].submit()
                                return false
                            })
                            .bind('reset',function(){
                                _.labels.removeClass(_.invalidCl)                                   
                                _.labels.each(function(){
                                    var th=$(this)
                                    _.hideErrorFu(th)
                                    _.hideEmptyFu(th)
                                })
                            })
                        _.form.trigger('reset')
                    }
                }
            _.me||_.init(_.me=th.data({forms:_}))
            typeof o=='object'
                &&$.extend(_,o)
        })
    }
})(jQuery)
$(window).load(function(){  
             $('#contact-form').forms({
         ownerEmail:'#'
         })
   })

我的问题是我想在表单顶部添加选择,这将更改邮件的主题,以便可以将它们分类到我的电子邮件帐户上的特定邮箱中。

我尝试添加到 forms.js 但没有效果,也许我做错了。除了 HTML 表单和 MailHandler 之外,所有代码都与我下载模板时的一样。虽然 MailHandler 在我添加选择之前就工作了,但从那以后我就没有改变它。

我不太擅长 JavaScript。HTML 和 PHP 我很好,但 JavaScript 我是新手。我不知道这是 JavaScript 问题还是什么,我猜这是所有功能所在。

感谢您的帮助,不要害怕询问更多信息。

4

2 回答 2

0

我设法通过一个简单的 JS 修复自己解决了这个问题。

在 HTML 表单中,我添加了以下内容:

<label class="topic">
    <input type="text" id="topicInput" class="hidden" /><br>
    <span class="error">*This is not an option</span>
    <span class="empty">*This field is required.</span>
</label>

在CSS中我添加了这个:

.hidden {
    display:none;
    width:0px;
    height:0px;
}

和 forms.js 我改变了提交功能:

submitFu:function(){
    _.validateFu(_.labels)                          
    if(!_.form.has('.'+_.invalidCl).length)
        $.ajax({
            type: "POST",
            url:_.mailHandlerURL,
            data:{
                topic:_.getValFromLabel($('.topic',_.form)),
                name:_.getValFromLabel($('.name',_.form)),
                email:_.getValFromLabel($('.email',_.form)),
                phone:_.getValFromLabel($('.phone',_.form)),
                fax:_.getValFromLabel($('.fax',_.form)),
                state:_.getValFromLabel($('.state',_.form)),
                message:_.getValFromLabel($('.message',_.form)),
                owner_email:_.ownerEmail,
                stripHTML:_.stripHTML
            },
            success: function(){
                _.showFu()
            }
        })          
}

对此

submitFu:function(){
            /* START ADDED */
    var selOption = document.getElementById('topic');
    var selVal = selOption.options[selOption.selectedIndex].value;

    document.getElementById('topicInput').value = selVal;
            /* END ADDED */

    _.validateFu(_.labels)                          
    if(!_.form.has('.'+_.invalidCl).length)
        $.ajax({
            type: "POST",
            url:_.mailHandlerURL,
            data:{
                topic:_.getValFromLabel($('.topic',_.form)),
                name:_.getValFromLabel($('.name',_.form)),
                email:_.getValFromLabel($('.email',_.form)),
                phone:_.getValFromLabel($('.phone',_.form)),
                fax:_.getValFromLabel($('.fax',_.form)),
                state:_.getValFromLabel($('.state',_.form)),
                message:_.getValFromLabel($('.message',_.form)),
                owner_email:_.ownerEmail,
                stripHTML:_.stripHTML
            },
            success: function(){
                _.showFu()
            }
        })          
}
于 2013-07-15T23:07:58.923 回答
0
if($_POST['topic']!='nope'){
        $messageBody .= '<p>topic: ' . $_POST["topic"] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
}

将以上内容添加到您的代码中。然后它将获取选择数据。

于 2013-07-15T13:52:03.503 回答