【问题标题】:JS AJAX: promise dependant submit always submittedJS AJAX:承诺依赖提交总是提交
【发布时间】:2020-05-24 19:37:50
【问题描述】:

最后,我设法做到了:

function validar(dato_a_validar, url, secc)
{
        var datastr = "secc=" + secc + "&dato=" + dato_a_validar;
        return new Promise(function(resolve, reject) {
                $.ajax({
                        type:'GET',
                        url:url,
                        data:datastr,
                        success:function(response) { resolve(response); },
                        error:function(response) { reject(response); }
                });
        });
}

async function check_submit()
{
        init(); // sets some global variables
        errores_personal_cnt = 0; // error counter

        var dni_ctl = document.getElementById("frm_funcionario_dni");
        var dni = dni_ctl.value;

        dni_ctl.style.borderColor = "black";
        dni_ctl.style.backgroundColor = "none";


        const estado = await validar(dni, url_validacion, "dni")
                .then(salida => estadoValidacion(dni_ctl, salida)) // estadoValidacion() sets some colour and form control title
                .catch(error => estadoValidacion(dni_ctl, "error"));
        $.when(estado).done(console.log("Errores: " + errores_personal_cnt));
        return false; // this is set for tests purposes, but is always ignored.
}

onsubmit 事件中,async function check_submit() 被调用。 validar(...) 函数返回一个 promise(我猜),并使用 .then().catch() y handle 两个结果。但是,即使有错误的字段,也会提交表单。

我认为表单总是提交的原因是因为我在某处有一些错误的代码,但我不知道在哪里。

谢谢!

【问题讨论】:

  • ajax调用是用来向服务器提交数据还是仅仅做表单验证?
  • 只是表单验证。如果所有字段都正确,计数器errores_personal_cnt == 0check_submit() 应该return true; 并提交。

标签: javascript ajax promise onsubmit


【解决方案1】:

用一个例子来解释假设我有一个我使用基于承诺的方法验证的表单。假设validar() 是一个执行一些验证并需要 3 秒的函数(我有很多你知道的字段!)。但是当这样使用时它失败了!请参阅下面的 cmets 了解为什么会这样。

<form action="google.com" id="frm">
  <input id="txt">
  <button type="submit">submit</button>
</form>

<script>
  document.getElementById('frm').onsubmit = () => {
    var check = check_submit();
    console.log(check); //Promise {<pending>}
    console.log(check ? true : false) // which is evaluates to true! (check ? true : false) <-- true
    //So browser proceeds with form's default behavior which is to submit on google.com
  }

  function validar() {
    return new Promise(function(resolve, reject) {
      setTimeout(() => resolve(false), 3000)
    });
  }

  async function check_submit() {
    var result = validar(); // <-- this line NEVER WAITS for the promise of validar to get resolve() 'ed 
    // instead its current value which is Promise {<pending>}  is used immediatly and RETURNED!
    return result;
  }
</script>

那么如何让它工作呢? 这很简单,只需通过在onsubmit 无条件中返回 false 来停止默认行为,并在 promise 值得到解决时手动提交表单(如果有效)

<form action="google.com" id="frm">
  <input id="txt">
  <button type="submit">submit</button>
</form>

<script>
  document.getElementById('frm').onsubmit = () => {
    check_submit(); //<-- will handle our form submission business
    return false; //unconditional
  }

  function validar() {
    return new Promise(function(resolve, reject) {
      setTimeout(() => resolve(false), 3000)
    });
  }

  async function check_submit() {
    var result = await validar(); //<-- this line NOW WAITS (due to await) for the promise of validar to get resolve() 'ed
    if (result) {
      alert('submitting form as validar returned true')
      document.getElementById('frm').submit(); // submit manully as promise'd value returned true
    } else
      alert('meh')
  }
</script>

【讨论】:

  • 太棒了!我认为它现在正在乞求工作。现在我遇到了一个小问题:手册submit() 不会将表单发送到正确的 URL,而是重新加载表单。
  • 我的错误:错误的操作。抱歉,我错过了很多修改。
  • 是的,它运行良好。我要感谢 Viney,特别感谢 @mhSangar 对我的帖子的跟进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多