我正在尝试将确认JSON对象返回给我的AJAX函数。出于某种原因,即使帖子成功(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
}
});
答案 0 :(得分:4)
问题是我没有使用相对网址作为目标。我认为这个问题是跨域脚本问题。我将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;
}
});
答案 1 :(得分:0)
error
回调最多需要三个参数:XHR对象,错误字符串和可选的异常对象。接受最后两个,他们应该告诉你发生了什么。
您可能还想使用Firebug,Dragonfly或Chrome的开发人员工具等调试程序来查看请求是否与您的想法一样成功。