2014-03-01 29 views
0

我使用這個代碼:JQuery的AJAX提交功能添加驗證

function submitForm() { 
    $.ajax({type:'POST', 
      url: 'index.php', 
      data:$('#ContactForm').serialize(), 
      success: function(response) { 
       $('#ContactForm').find('.form_result').html(response); 
      }} 
    ); 
    return false; 
} 

它運作良好,但我怎麼去添加例如...驗證提醒,如果用戶名或密碼是空的?

我知道這裏有很多類似的腳本,但是想特別將它添加到這個腳本中。

+0

的例子或低於之前或Ajax調用後,應驗證呢? – anthonygore

回答

1
function submitForm() { 
if(!$("#name").val()){ 
    alert("name field is empty."); 
    return false; 
}  


$.ajax({type:'POST', 
    url: 'index.php', 
    data:$('#ContactForm').serialize(), success: function(response) { 
    $('#ContactForm').find('.form_result').html(response); 
    }}); 

    return false; 
} 
2

使用beforeSend()

function submitForm() { 
    $.ajax({type:'POST', 
     url: 'index.php', 
     data:$('#ContactForm').serialize(), 
     success: function(response) { 
      $('#ContactForm').find('.form_result').html(response); 
     }}, 
     beforeSend: function(){ 
     if(!$("#name").val()){ 
      alert("name field is empty."); 
      return false; 
      }  
     } 
    ); 
return false; 
} 
0

你有AJAX調用語句

例如之前執行驗證

function submitForm() { 

var username=$('#id').value; 
if(username!='') 
{ 
    $.ajax({type:'POST', 

      url: 'index.php', 

      data:$('#ContactForm').serialize(), success: function(response) { 

       $('#ContactForm').find('.form_result').html(response); 

      }}); 
} 
else 
{ 
alert("Please Enter Username"); 
} 

      return false; 
    } 
0

你可能想要做這樣的事情

function submitForm() { 
    if (inputIsValid()) { 
     sendAjaxRequest(); 
    } else { 
     ShowMessage(); 
    } 
} 

function sendAjaxRequest(parameters) { 

    $.ajax({ 
     type: 'POST', 
     url: 'index.php', 
     data: $('#ContactForm').serialize(), 
     success: function (response) { 
      $('#ContactForm').find('.form_result').html(response); 
     } 
    }); 
} 

function inputIsValid() { 
    return $("#username").val() && $("#password").val(); 
} 

function ShowMessage() { 
    alert("Please provide username and password"); 
} 
0

使用這個鏈接引用http://jsfiddle.net/RH8Dy/查看定腳本

function submit() 
{ 
var username = document.getElementById("txtusername").value; 
var password = document.getElementById("txtpassword").value; 
if(username == "") 
{ 
alert("enter username"); 
} 
if(username == "") 
{ 
alert("enter username"); 
} 
else if(password == "") 
{ 
    alert("Enter Password"); 
} 
else 
{ 
//ajax call 
} 
}