我目前正在嘗試使用JQuery/Ajax來調用PHP(CodeIgniter)函數並返回一個數組或一個使用JSON的布爾,我需要一點點(或者可能是很多)的幫助。JSON/AJAX和PHP與CodeIgniter之間的JSON
我有一個基本的電子郵件形式(名稱/電子郵件/消息)在一個jQuery對話框......
function emailForm() {
$('#emailDialog').dialog({
autoOpen: false,
height: 450,
width: 300,
position: ['center-top'],
show: 'fade',
title: 'Contact Us',
modal: true,
buttons: {
Send: function() {
sendEmail();
},
Reset: function() {
clearForm('email');
}
}
});
$('#emailDialog').dialog('open');
}
此使用Ajax提交到使用form_validation,要麼返回PHP/CI一個笨控制器在陣列(JSON)錯誤或發送郵件,並返回基於它的成功布爾...
class Email extends CI_Controller {
function index() {
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() == false) {
$data = array(
'name' => form_error('name'),
'email' => form_error('email'),
'message' => form_error('message')
);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($data);
return false;
} else {
$this->load->library('email');
$this->email->set_newline("\r\n");
$name = $this->input->post('name');
$email = $this->input->post('email');
$message = $this->input->post('message');
$this->email->from($email, '...');
$this->email->to('...');
$this->email->subject('...');
$this->email->message($message);
if ($this->email->send() == false) {
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(false));
} else {
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(true));
}
}
}
}
我想阿賈克斯解析返回和相應的行爲基於以下代碼然而,當我提交一個空白表格(這應該會導致錯誤),用戶代理總是ev對else子句(指示郵件已成功發送)而不是初始if子句(解析JSON數組並呈現HTML)產生影響。我嘗試過幾種不同的if/else if/else配置,無濟於事。此外,調試時,郵政實際上是顯示空白值爲每個參數,以及響應和JSON顯示什麼,我覺得是正確的數據...
POST:
email
message
name
迴應:
{"name":"The Name field is required.","email":"The Email field is required.","message":"The Message field is required."}
JSON:
name "The Name field is required."
email "The Email field is required."
message "The Message field is required."
我似乎無法確定爲什麼我的阿賈克斯回報總是評估爲真,所以任何幫助將不勝感激。先謝謝你!
請不要downvote我太嚴厲,我是很新,SO
@jbeckom高興能幫上忙! – Gabtheviking
FANTASTICO !!!!!並感謝讓我接觸CI的方式,這樣更容易! – jbeckom