我正在使用 CodeIgniter 并尝试使用 jquery$.ajax()
函数捕获从控制器返回的 JSON 值。这是我下面的“登录/进程”控制器
public function process() {
$this->form_validation->set_rules('email','Email Address','trim|required|xss_clean');
$this->form_validation->set_rules('passwd','Password','trim|required|xss_clean|md5|callback_check_database');
$red = ($this->input->post('redirect_url')) ? $this->input->post('redirect_url') : null;
if ($this->form_validation->run() == false) {
$output = '{ "success": "no", "redirct": "' . $red . '", "err" : "' .validation_errors() . '" }' ;
} else {
//Go to private area
$output = '{ "success": "yes", "redirct": "account" , "err" : ""}';
}
}
header('Content-Type: application/json', true);
echo json_encode($output);
}
}
以下是我的部分观点:
<script type='text/javascript' language='javascript'>
$(document).ready(function() {
$("#LoginForm").on("submit",function() {
var datastring = 'email='+$("#email").val()+'&passwd='+$("#passwd").val()+'&redirect_url='+$("#redirect_url").val();
$.ajax({
type: "POST",
url: "<?= base_url("login/process") ?>",
dataType: "json",
data: datastring,
cache: false,
success: function(output) {
// alert(output.success);
if (output.success == 'yes') {
document.location.href=output.redirct
}
if (output.success == 'no') {
alert(output.err)
}
}
})
return false; // To prevent form submission
})
});
</script>
当我尝试使用 FireBug 进行调试时,以下是我得到的 POST 响应
"{ \"success\": \"no\", \"redirct\": \"messaging.php\", \"err\" : \"<p>The Password field is required.<\/p>\n\" }"