仅在用户确认警报后才触发POST请求

时间:2020-03-01 19:38:20

标签: javascript forms vuejs2 axios alert

我有一个带有提交按钮的Vue.js表单。单击后,将发送POST axios请求,并在呼叫有效时触发视觉警报。

一切正常,但有一点点细节。在用户单击警报弹出窗口中的“确定”之后,才发送POST请求。这不是预期的行为。该请求应一直发送,只要它是有效的呼叫,并且弹出窗口只是视觉确认。

您是否知道警报为何触发请求?谢谢!

submitForm(formName) {
  this.$refs[formName].validate(valid => {
    if (valid) {
      axios.post(
        "https://dummy.com",
        { name: this.ruleForm },
        {
          headers: {
            "Content-type": "application/json"
          }
        }
      );
      alert(
        "Success!"
      );
    } else {
      alert("Error at submit. Check required fields.");
      console.log("Error at submit. Check required fields.");
      return false;
    }
  });
},

奖金问题:您知道在用户确认警报后触发重定向的简单方法吗? :D

2 个答案:

答案 0 :(得分:0)

axios.post是异步的。结果返回时,您可能应该调用成功警报:

 axios.post(
    "https://dummy.com",
    { name: this.ruleForm },
    {
      headers: {
        "Content-type": "application/json"
      }
    }
  ).then(res => {
     alert(
      "Success!"
     );
  }).catch(err => console.error(err)) // handle error here

此外,警报会阻止进一步执行,直到用户单击“确定”(同步)为止。

答案 1 :(得分:0)

submitForm(formName) {
  this.$refs[formName].validate(valid => {
    if (valid) {
      axios.post(
        "https://dummy.com",
        { name: this.ruleForm },
        {
          headers: {
            "Content-type": "application/json"
          }
        }
      ).then(function(res){
          alert(
               "Success!"
                       );
              //write your code - response code is 200
    }).catch(function(err){
               alert(
                  "Error!"
                      );
               //write your code - response code != 200
     });

    } else {
      alert("Error at submit. Check required fields.");
      console.log("Error at submit. Check required fields.");
      return false;
    }
  });
},