douduan5073 2013-12-31 15:49
浏览 67
已采纳

Access-Control-Allow-Origin,mailHandler.php和forms.js

I have a really weird bug. I've been having trouble with this HTML5 template I've downloaded in terms of the contact form and MailHandler.php. I've done inspect element in Chrome and I keep getting the error "Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.", even though the files are in the same directory. And I've definitely changed the PHP to add a header and replaced all the placeholder email addresses with my own, but I'm not getting anything in my inbox.

Thanks so much for all your help!

This is 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:'matthewkol186@gmail.com',
                    stripHTML:true,
                    smtpMailServer:'localhost',
                    targets:'input,textarea',
                    controls:'a[data-type=reset],a[data-type=submit]',
                    validate:true,
                    rx:{
                        ".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: /*"../bat/MailHandler.php"*/_.mailHandlerURL,
                                data:{
                                    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:'matthewkol186@gmail.com'
         })
   })

This is MailHandler.php:

<?php
     header('Access-Control-Allow-Origin: *');  
    ini_set('display_errors', 'On');
    error_reporting(E_ALL | E_STRICT);
    $owner_email = /*$_POST[*/"matthewkol186@gmail.com"/*]*/;
    $headers = 'From:' .$_POST["email"];
    $subject = 'A message from your site visitor ' .$_POST["name"];
    $messageBody = "";

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

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

    try{
        if(!mail($owner_email, $subject, $messageBody, $headers)){
            throw new Exception('mail failed');
        }else{
            echo 'mail sent you are a winner good job!!! yayyyyyyyyy';
        }
    }catch(Exception $e){
        echo $e->getMessage() ."
 you suck";
    }
?>

I also receive this error afterwards, although I don't know where the XML is coming from: "XMLHttpRequest cannot load file:///Users/john/Documents/SkyDrive/Synapps/codester-free-responsive-bootstrap-template/codester/bat/MailHandler.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."

  • 写回答

1条回答 默认 最新

  • douyou2234 2013-12-31 16:19
    关注

    It looks like you're attempting to run things directly off the filesystem instead of through a web server. Stuff requested with the file:// protocol has different rules and security restrictions to stuff requested with http://. Since you are at no point making any HTTP requests it's hardly surprising that you have no Access-Control-Allow-Origin header, hence the error message.

    Your PHP script will do nothing if it is not being executed by a web server. You will need to install a web server and PHP in order to make this work locally.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形