【问题标题】:form validation ajax submit表单验证ajax提交
【发布时间】:2017-03-23 12:07:09
【问题描述】:

我有一个表格。我需要设置表单验证输入

<input type="text" name="telefon" required="" placeholder="Telefon numaranız" class="form-control">

但是当我点击提交表单为空或不为空时发送。这是我的 JavaScript 代码

<script>
function uyem() {
      jQuery.ajax({
      type: 'POST',
      url: 'src/ajax/kayit.php',

      data: $('#uyelik-formu').serialize(),
      error:function(){ $('#sonuc').html("Bir hata algılandı."); },
      success : function (sonuc){
        if(sonuc == 'msms'){
          $("#mod-sms").modal('show');
        }
        if (sonuc == 'hatak'){
          $("#sonuc").html('<div role="alert" class="alert alert-danger alert-icon alert-icon-colored alert-dismissible"><div class="icon"><span class="mdi mdi-close-circle-o"></span></div><div class="message"><button type="button" data-dismiss="alert" aria-label="Close" class="close"><span aria-hidden="true" class="mdi mdi-close"></span></button><strong>Hata!</strong> E-posta yada telefon başka bir üye tarafından kullanılmakta.</div></div>');
        }
        if(sonuc == 'error'){
          $("#mod-error").modal('show');
          setTimeout(function() { location.reload() },4000);
        }
        if (sonuc == 'hata'){
          $("#sonuc").html('<div role="alert" class="alert alert-danger alert-icon alert-icon-colored alert-dismissible"><div class="icon"><span class="mdi mdi-close-circle-o"></span></div><div class="message"><button type="button" data-dismiss="alert" aria-label="Close" class="close"><span aria-hidden="true" class="mdi mdi-close"></span></button><strong>Hata!</strong> Geçerli bir e-posta ve telefon numarası giriniz.</div></div>');
          }
          }
      });
    }
    </script>

【问题讨论】:

  • Ajax 请求和普通请求不同。所需的 HTML 验证不适用于 ajax
  • 控制台有错误吗?
  • 您的真正问题是什么?你有错误吗?
  • 什么@SagarV?这是我第一次听说。
  • 没有错误。在控制台上

标签: javascript jquery ajax validation


【解决方案1】:

您可以使用preventDefault() 来阻止默认功能

$(function() {
$('form').submit(function(e) {
e.preventDefault();
var data = $('input[name="telefon"]').val();
if(data.length > 0)
{
  function uyem() 
}
else
{
  alert('Input are not valid');
}
});
});

【讨论】:

    【解决方案2】:

    你必须告诉你的表单是否需要提交。

    <form onSubmit="uyem()"></form>
    
    function uyem() {
        $.ajax({});
    
        return false;
    }
    

    返回false表示不提交表单,而true表示提交。

    【讨论】:

    • 或者,由于用户已经在使用 jQuery,他们可以在没有任何内联 JS 的情况下捕获点击事件。 :)
    • @JayBlanchard 我猜 OP 有&lt;input type="submit" onClick="uyem()"&gt;,所以基本上是一样的。但由于 OP 不提供此信息 - 我不会对此进行任何修复。
    • 是的 - 没有细节很难知道。
    猜你喜欢
    • 2011-12-15
    • 1970-01-01
    • 2011-02-22
    • 2014-09-10
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多