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

问题描述 投票:0回答:3

我有一个带有提交按钮的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

javascript forms vuejs2 axios alert
3个回答
0
投票

您将要在其回调中处理错误或成功响应。由于服务器调用未以正确的方式(异步)返回响应,因此不在发布调用之外。请查看此处的文档以获取示例...在您的情况下,您要将警报放置在第一个“ then”功能中。 -https://github.com/axios/axios

  axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response); //success
  })
  .catch(function (error) {
    console.log(error); //error
  });

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

此外,警报会阻止进一步执行,直到用户单击确定(它是同步的。)。>


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;
    }
  });
},
© www.soinside.com 2019 - 2024. All rights reserved.