2014-06-24 36 views
0

我有一個註冊表單,它從服務器端收到錯誤,如HTTP代碼400(錯誤請求),如果字段丟失。

也許不是必要的,但這裏的代碼:

HTML

<div class="row"> 
    <div class="col-md-4 col-md-offset-4"> 
     <h1 class="text-center">SIGNUP</h1> 
     <div class="well"> 
      <form role="form" id="signup_form"> 
       <div class="form-group"> 
        <input type="text" class="form-control" id="signup_name" name="fullName" placeholder="Full Name"> 
       </div> 
       <div class="form-group"> 
        <input type="email" class="form-control" id="signup_email" name="username" placeholder="Enter email"> 
       </div> 
       <div class="form-group"> 
        <input type="password" class="form-control" id="signup_password" name="password" placeholder="Password"> 
       </div> 
       <button type="submit" class="btn btn-default btn-block">Signup</button> 
       <div id="signup_error_message" class="alert alert-danger"></div> 
       <div id="signup_processing_message" class="alert alert-success">Processing...</div> 
      </form> 
     </div> 
     <p class="help-block text-center"><span class="glyphicon glyphicon-lock"></span> SSL Secure</p> 
    </div> 
</div> 

JS

$('#signup_form').submit(function (event) { 
    $('#signup_processing_message').show(); 
    event.preventDefault(); 
    var fieldValues = getFormObj('signup_form'); 
    $.ajax({ 
     type: 'post', 
     url: '/signup/local', 
     data: fieldValues, 
     success: function (response, textStatus, xhr) { 
     if (xhr.readyState === 4 && xhr.status === 0) { 
      alert('Aborted. Network issue.'); 
     } else if (response.message === 'success') { 
      if ($('#signup_error_message').is(':visible')) { 
      $('#signup_error_message').hide(); 
      } 
      $('#signup_processing_message').html('Success'); 
      setTimeout(function(){ window.location.href = '/'; }, 500); 
     } else { 
      // Could this ever happen? 
     } 
     }, 
     error: function (response) { 
     console.log(response); 
     if ($('#signup_processing_message').is(':visible')) { 
      $('#signup_processing_message').hide(); 
     } 
     if (response.status === 400) { 
      $('#signup_error_message').html('Please fill in the fields correctly.'); 
     } else { 
      $('#signup_error_message').html('Please fill in the fields correctly.'); 
     } 
     $('#signup_error_message').show(); 
     } 
    }); 
    }); 

// For forms - signup, login etc. Returns an obj with the name and value of each field in the form. 
function getFormObj(formId) { 
    var formObj = {}; 
    var inputs = $('#' + formId).serializeArray(); 
    $.each(inputs, function (i, input) { 
    formObj[input.name] = input.value; 
    }); 
    return formObj; 
}; 

至於服務器端,如果輸入的信息是好的,形式會成功,否則它可以返回類似於:http://screencast.com/t/sS5Vmar0Jk

錯誤的樂趣$ .ajax中的ction沒有檢測到HTTP錯誤。但是,當我重新啓動節點服務器時,會檢測到錯誤,並運行console.log(response)等。

有什麼想法?

+0

什麼是你的服務器端代碼試試?你結束了你的迴應?特別是錯誤處理部分。 – Zlatko

回答

0

使用

$.ajax({ 
    ... 
    data: JSON.stringify(fieldValues), 
    ... 
相關問題