CodeIgniter控制器 - 如何将状态传递回调用函数

时间:2011-05-24 03:28:49

标签: php jquery codeigniter

我使用CI框架将一些数据发布到控制器上的操作。帖子成功完成,但我想将状态返回给调用jQuery.post()。

使用firebug我可以看到帖子已经成功完成(200)但是我没有看到我正在返回的json。为什么我没有让json回来?

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


    if (valid_email($returnEmail))
    {
        send_email('me@my.com','Website Email From: '.$senderName, $message);
        $success = array('success'=>'Mail Sent');
        echo json_encode($success);
    }
    else
    {
        $errorMessage = array('error'=>'Invalid Email Address');
            echo json_encode($errorMessage);
    }
}

Ajax帖子

$.post("http://example.com/index.php/mail/sendmail",{senderName: senderName, returnEmail: senderAddr, message: message }, function(data){
if(data.status == "success")
{
    alert("mail sent.");
}
else
{
    alert("mail failure");
}
}); 

2 个答案:

答案 0 :(得分:0)

您可以使用$_GET代替$_POST进行测试,直到获得所需的结果。您的代码应该有效,除非:

  • 您尚未加载电子邮件帮助程序
  • 您使用的旧版PHP不支持json_*()
  • 区分大小写的方法(sendMail,而不是sendmail

我还建议您为JavaScript使用以下代码:

$.ajax({
    type: 'POST',
    url: "http://mysite.com/index.php/mail/sendmail",
    data: {senderName: senderName, returnEmail: senderAddr, message: message},
    dataType: "JSON",
    success: function(data){
        if(typeof data.error == "undefined"){
            alert("Mail failure");
        }
        else{
            alert("Mail sent");
        }
    },
    error: function(data){
        alert("Something went wrong"); // possible that JSON wasn't returned
    }
});

答案 1 :(得分:0)

问题在于网址。我想尝试从我的本地主机发布到'http://mysite.com'导致跨站点脚本安全问题。

我将url属性更改为相对属性,并且效果很好。

$.ajax({
    type: 'POST',
    url: "index.php/mail/sendmail",
    data: {senderName: senderName, returnEmail: senderAddr, message: message},
    dataType: "JSON",
    success: function(data){
        if(typeof data.error == "undefined"){
            alert("Mail failure");
        }
        else{
            alert("Mail sent");
        }
    },
    error: function(data){
        alert("Something went wrong"); // possible that JSON wasn't returned
    }
});