2014-06-27 31 views
0

假設我有一個登錄表單,其中有兩個表單元素,即用戶名和密碼。但在客戶端驗證我沒有設置用戶名所需的選項。我的目標是在做客戶端驗證之後,我想通過ajax從服務器端對此進行驗證,其中用戶名字段將在服務器端進行驗證,如果用戶名爲空,則將php檢查和響應作爲json。我想解析數據並顯示驗證錯誤,並顯示登錄身份驗證錯誤消息是否以登錄形式顯示給不同的div元素。但無法得到這個。請幫我解決這個問題。客戶端完成後服務器端的變化

$(document).ready(function(){ 

     // initialize validator and add the custom form submission logic 
      $("#LoginForm").validator().submit(function(e) { 

        var form = $(this); 

        // client-side validation passed 
         if (!e.isDefaultPrevented()) { 


          $.ajax({ 
           type: "POST", 
           url: "process.login.php", 
           data: $('#LoginForm').serialize(), 
           dataType: "json", 
           success: function(msg){ 

            if(parseInt(msg.status)==1) 
             { 
              window.location=msg.txt; 
             } 
           } 
          }); 


          // prevent default form submission logic 
          e.preventDefault(); 
         } 
        }); 

       }); 
+0

你有一個失蹤}成功:功能(味精){ –

+0

謝謝,更新了這段代碼。 –

回答

0

我想你想知道php(服務器)驗證響應如何工作?

<?php 

// your validation here ... 

$msg = array("status"=>1, "text"=>"some text here"); 

echo json_encode($msg); 
0

這可能有助於。我不得不欺騙中隱藏的表單變量您迴應,但你應該抓住信息和狀態,並處理它。也趕上服務器端的錯誤。

我也修正了你的驗證方式,但你可能想閱讀關於jQuery驗證器最佳實踐的文檔。

http://jsfiddle.net/Xedus129/y6fA3/

錯誤處理/成功的Ajax調用處理:

  success: function (msg) { 
       var status = parseInt(msg.status); 
       var message = msg.message; 
       return handleResponse(status,message); 
      }, 

      error: function (xhr, ajaxOptions, thrownError) { 
       //this is a fatal error 
       alert(xhr.status); 
       alert(thrownError); 
      } 

希望這是你問的是什麼,很難從你的問題告訴我們。

+0

我已經對密碼字段進行了客戶端驗證,即jquery檢查密碼字段是否爲空。如果空白,則顯示錯誤消息(默認驗證錯誤消息)或者使用這個'if($(this).valid()){'併發布到php頁面,其中名稱字段將被檢查如果空白,那麼它拋出一個msg格式的json,並傳遞給jquery驗證器,如{'username':'輸入用戶名'} –