jQuery-为什么总是调用Ajax()错误回调


jQuery - Why is the Ajax() error callback always called?

我正试图将一个确认JSON对象返回给我的AJAX函数。出于某种原因,即使post是成功的(200),也总是调用错误回调函数。我正在将返回的JSON记录到一个文件中进行复制,它看起来是正确的。我不明白为什么会发生这种事。有人能提个建议吗?

PHP控制器操作(CI):

public function sendMail()
    {
        $senderName = trim($_POST['senderName']);
        $returnEmail = trim($_POST['returnEmail']);
        $message = trim($_POST['message']);

        if (valid_email($returnEmail))
        {
            send_email('email@email.com','Website Email From: '.$senderName, $message);
            $success = array('success'=>'Mail Sent');
            //Debugging to file
            $myFile = "testFile.txt";
            $fh = fopen($myFile, 'w') or die("can't open file");
            $stringData = json_encode($success);
            fwrite($fh, $stringData);
            fclose($fh);

            echo json_encode($success);
        }
        else
        {
            $errorMessage = array('error'=>'Invalid Email Address');
            echo json_encode($errorMessage);
        }
    }

}

JS:

$.ajax({
                   type: "POST",
                   url: "http://domain.com/index.php/mail/sendmail",
                   data: {senderName: senderName, returnEmail: senderAddr, message: message },
                   dataType: "JSON",
                   success: function(msg){
                     console.log(msg);
                   },
                   error: function(data){
                        alert("Something went wrong"); // possible that JSON wasn't returned
                    }
                 });

问题是我没有为目标使用相对url。我认为这个问题是一个跨域脚本问题。我将url属性更改为index.php/mail/sendmail,一切都很好。

$.ajax({
               type: "POST",
               url: "index.php/mail/sendmail",
               data: {senderName: senderName, returnEmail: senderAddr, message: message },
               dataType: "JSON",
               success: function(msg){
                 console.log(msg);
               },
               error:function (xhr, ajaxOptions, thrownError){
                    var x = xhr;
                    var y = ajaxOptions;
                    var z = thrownError;
                }
             });

error回调最多占用三个参数:XHR对象、错误字符串和可选异常对象。接受最后两个,他们应该告诉你发生了什么。

您可能还想使用像Firebug、Dragonfly或Chrome的开发工具这样的调试器来查看请求是否像您想象的那样成功。