即使成功请求,也会调用jQuery ajax错误函数

时间:2012-07-19 09:25:52

标签: jquery ajax

我正在处理我希望在没有页面刷新的情况下发送的wordpress网站联系表单。 我设法让它工作,它发送邮件,但后来我想如果它没有成功,并添加了错误功能。现在,它每次调用错误函数,即使它设法发送邮件。 这是代码:

    $("#Submit").click(function () {
    var dataString = $('#knamecontactform').serialize();
    //alert (dataString);return false;
    $.ajax({
        type: "POST",
        url: "http://example.com/form.php",
        data: dataString,
        dataType: "text",
        error: function () {
            $('#messagenotsent').fadeIn(400);
        },
        success: function () {
            $('#knamecontactform')[0].reset();
            $('#messagesent').fadeIn(400);
        }


    });
    return false;

});

并且submitform.php:

<?php
$to = "mail@gmail.com";
$subject = "Message";
$message = 
$_POST['Nimi'] . "\n" .
$_POST['Puhelin'] . "\n" .
$_POST['Sposti'] . "\n" .
$_POST['Tiedot'];
$from = $_POST['Nimi'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo 'Mail sent.';
?>

1 个答案:

答案 0 :(得分:5)

除了上面提到的评论者(你的原始问题是跨域AJAX),你可能还想考虑使用更新的(在1.5版中引入)jQuery延迟处理AJAX事件的方式,因为错误:和成功:函数将在jQuery的未来版本中被弃用。除了更具前瞻性之外,我还认为它为您的代码提供了一点可读性。

而不是成功使用.done而不是错误使用.fail。请参阅下面的示例。

$.ajax({
  //all your regular ajax setup stuff except no success: or error:
 })
 .done( function (data, status) {
     //do whatever you want with the return data upon successful return
 })
 .fail( function (data, status) {
     //do whatever you want with the return data upon error
 });

有关详细信息,请查看jQuery docs on deferred objects

相关问题