首页 > 解决方案 > 带有 else 语句的 Ajax 请求响应不佳

问题描述

我正在使用带有表单的 Ajax 来向用户显示提交时是否一切正常(没有错误)或输入是否丢失。它应该是基本的。我正在使用 XMLHttpRequest 对象。表单有四个字段,都是必需的。我是使用 Ajax 的新手,您的帮助会非常棒

这是我的表格

<form method="POST">
        @csrf
        <!-- Intitulé du thème -->
        <input type="text" name="intitule" id="intitule" placeholder="Intitulé du thème" required><br>
        <!-- Catégorie -->
        <select name="categorie" required>
            <option value="">-- Catégorie --</option>
            <option value="web">Développement web</option>
            <option value="appMobile">Programmation application mobile</option>
            <option value="secure">Sécurisation</option>
            <option value="other">Autre</option>
        </select> <br>
        <!-- Filière désirée -->
        <input type="checkbox" name="filiere[]" id="GL" value="GL" required>
        <label for="GL">Génie Logiciel</label><br>
        <input type="checkbox" name="filiere[]" id="SI" value="SI" required>
        <label for="SI">Sécurité Informatique</label><br>
        <input type="checkbox" name="filiere[]" id="IM" value="IM" required>
        <label for="IM">Internet et Multimédia</label><br>
        <input type="checkbox" name="filiere[]" id="SIRI" value="SIRI" required>
        <label for="SIRI">Systèmes d'Information et Réseaux Informatiques</label><br>
        <!-- Descriptif -->
        <textarea name="description" id="description" placeholder="Description de la thématique" required></textarea><br>

        <input type="submit" name="submit" id="submit" value="Ajouter">
        <span id="error-message" class="text-danger"></span>
        <span id="success-message" class="text-success"></span>
    </form>

在我的 jquery 代码中,我声明一个变量itsChecked在复选框被选中或不选中时具有一个值。

<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(function (){
            var itsChecked = null;
            $('input[type=checkbox]').on('click', function(){
                if($('input[type=checkbox]:checked').length > 0){ //S'il y a au moins 1 ([...].length > 0) ckecked
                alert('At least one is checked');
                    itsChecked = 1;
                    $('#GL').removeAttr("required");
                    $('#SI').removeAttr("required");
                    $('#IM').removeAttr("required");
                    $('#SIRI').removeAttr("required");
                }
                else if(!$('input[type=checkbox]:checked').length > 0){ //S'il n'y a aucun checked (!(at least 1)>0)
                alert('None is checked');
                    itsChecked = 0;
                    $('#GL').attr('required','');
                    $('#SI').attr('required','');
                    $('#IM').attr('required','');
                    $('#SIRI').attr('required','');

            }
            });

对于 Ajax 部分,我使用了 XHR 对象。


            $('#submit').on('click', function(e){
                e.preventDefault();
                var xhr = getXMLHttpRequest();

                var titre = $('#intitule').val();
                var domaine = $('select[name=categorie]').val();
                var filiereChecked = [];
                $.each($("input[type='checkbox']:checked"), function(){            

                filiereChecked.push($(this).val());

                });
                var checked = filiereChecked.join(", ");
                var desc = $('#description').val();
                alert(itsChecked);

                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)){
                        // alert(xhr.responseText);
                        // console.log(xhr.responseText);
                        $('#error-message').html('');
                        $('#success-message').fadeIn().html(xhr.responseText);
                        setTimeout(function(){
                            $('#success-message').fadeOut('slow');
                        }, 2000);   
                        $('form').trigger('reset'); 
                    }
                    else if (titre == '' || domaine == '' || itsChecked == null || itsChecked == 0 || desc == ''){

                        $('#error-message').fadeIn().html('Tous les champs sont requis');
                        setTimeout(function(){
                            $('#error-message').fadeOut('slow');
                        },2000);
                        xhr.abort();
                    }
                };
                var url = "{{ route('themes.store') }}"; 
                var formValues = $("form").serialize();
                xhr.open('POST', url , true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send(formValues);

            });

我的问题出在 else 语句上。验证titre,domainedescok:我的意思是,当他们的字段没有被通知时,错误消息被返回并且用户必须填写所有这些。

复选框组例外。这是 itsChecked 变量来提供帮助。因此,当它为“null”或等于 0 时,应遵循相同的过程,用户必须正确填写。不知何故,当它没有被选中时,我收到了错误消息,但表单仍然在数据库中提交,并且数据库中的复选框字段为空(NULL)。我不明白我在这里做错了什么。感谢帮助

标签: jqueryajaxlaravel

解决方案


我真的认为你的逻辑有缺陷。您试图else在两个条件语句中都添加不必要的内容。此外,只要在send()条件语句之外调用提交按钮,就会发布表单。尝试了解表单验证的工作原理,特别是xhr.onreadystatechange类似的方法可以实现什么。以下是我如何看待您的问题:

HTML

<form method="POST">
    @csrf
    <!-- Intitulé du thème -->
    <input type="text" name="intitule" id="intitule" placeholder="Intitulé du thème" required>
    <br>
    <!-- Catégorie -->
    <select name="categorie" required>
        <option value="">-- Catégorie --</option>
        <option value="web">Développement web</option>
        <option value="appMobile">Programmation application mobile</option>
        <option value="secure">Sécurisation</option>
        <option value="other">Autre</option>
    </select>
    <br>
    <!-- Filière désirée -->
    <input type="checkbox" name="filiere[]" id="GL" value="GL" required>
    <label for="GL">Génie Logiciel</label>
    <br>
    <input type="checkbox" name="filiere[]" id="SI" value="SI" required>
    <label for="SI">Sécurité Informatique</label>
    <br>
    <input type="checkbox" name="filiere[]" id="IM" value="IM" required>
    <label for="IM">Internet et Multimédia</label>
    <br>
    <input type="checkbox" name="filiere[]" id="SIRI" value="SIRI" required>
    <label for="SIRI">Systèmes d'Information et Réseaux Informatiques</label>
    <br>
    <!-- Descriptif -->
    <textarea name="description" id="description" placeholder="Description de la thématique" required></textarea>
    <br>

    <input type="submit" name="submit" id="submit" value="Ajouter">
    <span id="error-message" class="text-danger"></span>
    <span id="success-message" class="text-success"></span>
</form>

Javascript:

<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(() => {
  var itsChecked = null

  $('input[type=checkbox]').on('click', () => {
    if ($('input[type=checkbox]:checked').length > 0) {
      //S'il y a au moins 1 ([...].length > 0) ckecked
      alert('At least one is checked')
      itsChecked = 1
      $('#GL').removeAttr("required")
      $('#SI').removeAttr("required")
      $('#IM').removeAttr("required")
      $('#SIRI').removeAttr("required")
    } else {
      //S'il n'y a aucun checked (!(at least 1)>0)
      alert('None is checked')
      itsChecked = 0
      $('#GL').attr('required', '')
      $('#SI').attr('required', '')
      $('#IM').attr('required', '')
      $('#SIRI').attr('required', '')

    }
  })

  $('#submit').on('click', (e) => {
    e.preventDefault()
    let xhr = new XMLHttpRequest()
    const titre = $('#intitule').val()
    const domaine = $('select[name=categorie]').val()
    let filiereChecked = []

    $.each($("input[type='checkbox']:checked"), (i, elem) => {
      filiereChecked.push($(elem).val())
    })
    const checked = filiereChecked.join(", ")
    const desc = $('#description').val()
    alert(itsChecked)

    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
        $('#error-message').html('')
        $('#success-message').fadeIn().html(xhr.responseText)
        setTimeout( () => {
          $('#success-message').fadeOut('slow')
        }, 2000)
        $('form').trigger('reset')
      }
    }
    if (titre === '' || domaine === '' || itsChecked === null || itsChecked === 0 || desc === '') {
      $('#error-message').fadeIn().html('Tous les champs sont requis')
      setTimeout(() => {
        $('#error-message').fadeOut('slow')
      }, 2000)
      xhr.abort()
    } else {
      const url = "{{ route('themes.store') }}"
      const formValues = $("form").serialize()
      xhr.open('POST', url, true)
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
      alert('form sent')
      xhr.send(formValues)
    }
  })
})
</script>

等等,这可以满足您的需求。这是一个工作小提琴


推荐阅读