Ajax问题:解析JSON请求失败

时间:2016-11-01 15:38:46

标签: php json ajax

我的代码存在问题。我想发一封电子邮件,但它不起作用...... 我从2天开始搜索,但我没有找到问题!

非常感谢您的帮助!

HTML表单:

<div id="contact">
    <form action="#" method="post">

                <div id="contact-input">
                 <!--[if IE]>
                    <label for="name">Name</label>
                <![endif]-->
                  <input type="text" name="contact[name]" id="name" placeholder="Name (required)" >
                   <!--[if IE]>
                        <label for="email">Email</label>
                    <![endif]-->
                  <input type="text" name="contact[email]" id="email" placeholder="Email (required)">
                   <!--[if IE]>
                        <label for="subject">Subject</label>
                    <![endif]-->
                  <input type="text" name="contact[subject]" id="subject" placeholder="Subject" >
                </div>
                <div id="contact-textarea">
                 <!--[if IE]>
                        <label for="message">Your Message Here</label>
                    <![endif]-->
                  <textarea name="contact[message]" id="message" cols="39" rows="4" placeholder="Your Message"></textarea>
                </div>
                <div id="contact-submit">
                  <div>
                    <input name="submit" type="submit" id="submit" tabindex="5" value="Post Comment" class="comment-submit small button">
                  </div>
                </div>
              </form>
</div>

Ajax请求:

$("#contact form").submit(function()
{
    var form = $(this);
    var formParams = form.serialize();
    console.log(formParams);
    $.ajax(
    {
        url: 'contact.php',
        type: 'POST',
//traditional: true,
        data: formParams,
        dataType: 'json',
        success: function(data){
            console.log("success");
            var response = jQuery.parseJSON(data);              
            if(response.success)
            {   
                console.log("win");
                $('#contact form').slideUp().height('0');
                $('#contact .result').append(mailSuccess);
            }
            else
            {
                console.log("lose");
               for(i=0; i<response.errors.length; i++){
                 if(response.errors[i].error == 'empty_name'){                          
                   mailResult.append(nameError);
                 }
                 if(response.errors[i].error == 'empty_email'){                          
                   mailResult.append(emailError);
                 }
                 if(response.errors[i].error == 'empty_subject'){                          
                   mailResult.append(subjectError);
                 }
                 if(response.errors[i].error == 'empty_message'){                          
                   mailResult.append(messageError);
                 }
                 if(response.errors[i].error == 'invalid'){
                    mailResult.append(invalidEmailError);
                 }
               }
            }
        },
        error: function(x,e) {
//console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
            if (x.status==0) {
                console.log('You are offline!!\n Please Check Your Network.');
            } else if(x.status==404) {
                console.log('Requested URL not found.');
            } else if(x.status==500) {
                console.log('Internel Server Error.');
            } else if(e=='parsererror') {
                console.log('Error.\nParsing JSON Request failed.');
            } else if(e=='timeout'){
                console.log('Request Time out.');
            } else {
                console.log('Unknow Error.\n'+x.responseText);
            }
        }

    })
    return false;
});

PHP代码(contact.php):

<?php
header('Content-type: text/json');
define('TO_EMAIL', '"Email" <emailadresse@gmail.com>');

class Mailer{

private $_params;
private $_errors;

public function __construct(){
    $this->_params = $this->LoadParams();
    $this->_errors = array();
}

public function run(){  
    if($this->Validate()){
        $res = $this->SendEmail();
        if($res === true)
            $this->OnSuccess();
        else
            $this->OnError();   
    }else
        $this->OnError();       
}

private function LoadParams(){
    ?>
    <script>
        alert('form : ' + <?php print $_POST['contact']; ?>);   
    </script>
<?php
    return $_POST['contact'];
}

private function Validate(){
    if(!(isset($this->_params['name']) && ($this->_params['name'] != '')))
        $this->_errors['name'] = 'empty_name';
    if(!(isset($this->_params['email']) && $this->_params['email'] != ''))
        $this->_errors['email'] = 'empty_email';
    else{
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp,$this->_params['email']))
            $this->_errors['email'] = 'invalid';
    }
    if(!(isset($this->_params['subject']) && $this->_params['subject'] != ''))
        $this->_errors['subject'] = 'empty_subject';
    if(!(isset($this->_params['message']) && $this->_params['message'] != ''))
        $this->_errors['message'] = 'empty_message';

    return (count($this->_errors) == 0);
}

private function SendEmail(){
    $headers = 
        'From: "' . $this->_params['name'] . '" <' . $this->_params['email'] . ">\r\n" .
        'Reply-To: "' . $this->_params['name'] . '" <' . $this->_params['email'] . ">\r\n" .
        'X-Mailer: PHP/' . phpversion();

    $to = TO_EMAIL;       
    return mail($to, $this->_params['subject'], $this->_params['message'], $headers);
}

private function OnSuccess(){        
    echo '{"success": true}';
}

private function OnError(){
    $response = '{';
    $response .= '"success": false, "errors": [';

    foreach($this->_errors as $key => $value) {  
        $response .= "{ \"field\": \"$key\", \"error\": \"$value\"},";
    }
    if(count($this->_errors) > 0)
        $response = substr($response, 0, -1);
    $response .= ']}';

    echo $response;
//        echo json_encode(array("success"=>"false"));
}

}

$mailer = new Mailer();
$mailer->run();

?>

0 个答案:

没有答案