duanhuizhe6767 2012-09-25 00:04
浏览 21
已采纳

有了jQuery,AJAX和PHP的这个组合,我如何捕获来自PHP的错误?

I handle it if the PHP returns successfully, but as far as errors go I'm a little confused as to what I should be doing.

What I was thinking of doing since the following code for error: doesn't work, was in my PHP setting the mail function equal to a variable in order to save the result of the function. Then in my jQuery, testing the result of the variable to find whether or not it's true.

However this would all occur under success: when it seems like clearly error should be handling this.

How do I have it so success: handles the successes correctly and displays a message while error: will handle the errors by returning the errors then I'll be able to display them to the user.

Also bonus points if you can tell me if my .html() function is done well? It looks messy formatting-wise, but I can't seem to figure a nicer way to do it.

jQuery:

// Following section submits form without refreshing page
var dataString = "name=" + nameVal + "&email=" + emailVal + "&message=" + messageVal;  
$.ajax({  
    type: "POST",  
    url: "mail.php",  
    data: dataString,  
    success: function() { 
        $(".contact-form").hide();
        $(".alt-contact").hide();
    // Inserts divs making up the success message for the form submission
        $(".contact-form").html("<div class='success-message'><div class='success-image'></div><div class='success-title'>Success! The message has been sent!</div><div class='success-body'>I'll get back to you right away.</div></div>");
        $(".contact-form").fadeIn(500);
    }
    error: function() {
        $(".contact-form").hide();
        $(".alt-contact").hide();
        // Inserts divs making up the success message for the form submission
        $(".contact-form").html("<div class='error-message'><div class='error-image'></div><div class='error-title'>Success! The message has been sent!</div><div class='error-body'>I'll get back to you right away.</div></div>");
        $(".contact-form").fadeIn(500);
    }
});
return false;

PHP:

<?php

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $recipient = 'me@christianselig.com';
    $subject = 'Message From Website';
    $body = '<b>From:</b> ' . $name . '

' . $message;
    $headers = 'From: ' . $email . '
';
    $headers .= 'Content-type: text/html; charset=UTF-8' . '
';

    mail($recipient, $subject, $body, $headers);

?>
  • 写回答

1条回答 默认 最新

  • douren1928 2012-09-25 00:18
    关注

    Any error messages will stil be pumped back to "success" in the ajax call. (Error function is for "call did not work" or "unexpected response from server")

    You should check your script to report both success and error status to the script. This is easiest handled in JSON, but for that you need to write a custom error handler that spits out JSON.

    For now, make it simple with:

    if (@mail($recipient, $subject, $body, $headers)) {
         return json_encode(array('success' => 1));
    } else {
         return json_encode(array('success' => 0));
    } 
    

    then change you JS to

    // Following section submits form without refreshing page
    var dataString = "name=" + nameVal + "&email=" + emailVal + "&message=" + messageVal;  
    $.ajax({  
        type: "POST",  
        url: "mail.php",  
        data: json,    // CHANGED TYPE HERE
        success: function(data) { 
              if (data.success) {
                    // WORKED
               } else {
                    // FAILED TO SEND
               }
            $(".contact-form").fadeIn(500);
        }
        error: function() {
               // was not JSON, you got some other error
        }
    });
    return false;
    

    Edit in response to comment question

    By default error will be called if there is an invalid response (e.g. 404 page not found, 500 server error). As I added "datatype: json" then error will also be returned if the response can't be parsed as JSON. if you left datatype as 'dataString' then you may of may not hit error so adding the JSON type makes it more reliable. Regardless, JSON is easier to handle in Javascript and a known structure is best - so always try to return JSON (unless you need HTML, XML or another known structure). Strings are least reliable.

    It's a litle more complicated at first as regular PHP errors will also be sent back as "strings" and not valid JSON; so these go to error where you have to handle it. I've avoided this in hte exampel above by hiding errors from the mail call in your code with @, and handled it specifically. For my projects I have custom error handler that traps errors and spits back the response in JSON in a known structure - this then returns in success, all my AJAX calls check for 'data.error' which means it went though the error handler, and can be handled accordingly. But for now, just handle via the error in the AJAX and use Charles (Mac OS) or Fiddler (Windows) or the network sniffers in the browsers for debugging.

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

报告相同问题?

悬赏问题

  • ¥15 配置FPT报错,该如何处理
  • ¥15 请大家看一下这个代码咋写,一点思路都没有,最好能做一下,不要伪代码,有偿
  • ¥15 有偿请人帮写个安卓系统下禁止装软件及禁止拷入文件的程序
  • ¥100 用 H.265 对音视频硬编码 (CUDA)
  • ¥20 mpich安装完成后出问题
  • ¥15 stm32循迹小车代码问题
  • ¥15 输入一堆单词,使其去重输出
  • ¥15 qc代码,修改和添加东西
  • ¥50 Unity的粒子系统使用shadergraph(内置管线)制作的一个顶点偏移shader,但是粒子模型移动时,顶点也会偏移
  • ¥15 如何用python处理excel的数据(极值标准化)