2010-02-25 77 views
2

我們使用jquery .load()一個形式爲一個divjquery的交笨驗證

然後,我們使用jQuery .POST()的形式向笨控制器即/應用/後

我們然後希望Codeigniter執行驗證,但不確定如何返回到頁面以顯示驗證錯誤?如果re .load()控制器不會重新初始化對象,我們會丟失數據?

我們以錯誤的方式接近這個嗎?

回答

1

將驗證消息存儲在來自控制器的會話中,然後在相應的視圖/頁面上顯示它們,但是如果所有驗證都由用戶正確完成,則應該再次銷燬會話。

6

我打算採取一些自由回答這個問題,因爲我不認爲我理解它。

首先,我對$.post()瞭解不多,所以我會回答你的問題,就好像你是我們使用$.ajax(),因爲我知道這是我所知道的,我很確定它們是相似的。

我們接着要笨執行 驗證,但不知道如何 返回一個頁面來顯示 驗證錯誤?

您不返回到頁面以顯示錯誤,您將它們回顯出來以便jQuery可以接收輸出(如CI視圖文件),然後您可以根據需要處理結果。

使用$.ajax(),這裏是我會做什麼..

CI控制器:

if(! $this->form_validation->run($my_form_rules)) 
{ 
    // Set the status header so $.ajax() recognizes it as an error 
    $this->output->set_status_header(400); 

    // The error string will be available to the $.ajax() error 
    // function in the javascript below as data.responseText 
    echo validation_errors(); 

    exit(); 
} 
else 
{ 
    // Do something with the post data 
    $result = $this->do_something(); 

    // Set the status header so $.ajax(0 recognizes a success 
    // and set the header to declare a json response 
    $this->output->set_status_header(200); 
    $this->output->set_header('Content-type: application/json'); 

    // Send the response data as json which will be availible as 
    // var.whatever to the $.ajax() success function 
    echo json_encode($result); 

    exit(); 
} 

阿賈克斯:

$.ajax({ 
    data: myPostDataObj, 
    dataType: "json", 
    type: "POST", 
    success: function(data) { 
     alert(data.message); 
    }, 
    error: function(data) { 
     alert(data.responseText); 
    } 
}); 

您可以在jQuery的here閱讀更多關於$.ajax(),但基本上,您將發佈的數據發送到您設置的任何控制器,它將採集該數據,並通過驗證過程運行ss,如果失敗,它會迴應一些標準文本,ajax會將其作爲var.responseText發送到您的錯誤函數。

如果它通過驗證,你會對發佈數據做一些事情,然後返回你想要的任何結果作爲一個json對象,可以很容易地使用你的javascript函數。

我認爲這可能是一個更好的解決方案,我希望這有助於解釋一些事情。我希望。

+0

哎呀!我可能誤解了這個問題.... – bschaeffer 2010-02-25 04:01:39

+0

bschaeffer非常漂亮! – 2010-02-25 16:05:44