通过页面传递变量时,VueJS Axios POST返回NULL

时间:2018-10-25 16:18:51

标签: javascript php vuejs2 axios

我已经花了几个小时来理解这一点,然后重新检查StackOverflow的答案。也尝试复制粘贴,没有用。

var app = new Vue({
  el: '#app',
  data: {
    jobtype_select: '',
    jobtype_list: [{
        id_JobType: 'JTY0001',
        name_JobType: 'Survey'
      },
      {
        id_JobType: 'JTY0002',
        name_JobType: 'Research'
      },
      {
        id_JobType: 'JTY0003',
        name_JobType: 'Maintenance'
      }
    ],
    woFormABCD: '',
    totallyRandom: 'Hello Heiayo'
  },

  methods: {
    recordTESTWo() {
      var form = new FormData();
      form.append('test', this.totallyRandom);
      axios.post('action.php',
          form
        )
        .then(function(response) {
          alert('Success!');
          console.log(response);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }

});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id='app'>
  <form method="post" action="action.php" @submit.capture='recordTESTWo'>
    <div class="">
      <label for="jobtype_id" class="control-label required"><strong>Choose Job Type</strong></label>
      <div v-for='jobtype in jobtype_list'>
        <label class="">
                            <input  type="radio" 
                                    id= 'jobtype_id'
                                    v-model= 'jobtype_select'
                                    :value="jobtype.id_JobType"
                                    name='jobtype_select' 
                                    > 
                            {{jobtype.name_JobType}}
                        </label>
      </div>
      <p> This is : {{jobtype_select}}</p>
    </div>
    <div>
      <button>Submit</button>
    </div>
  </form>
</div>

我想做的就是尝试将totallyRandom的值传递给下一页。就是action.php

<?php
    session_start();
    //$data = json_decode(file_get_contents("php://input"), TRUE);
    printf("This is GET: \r\n");
    var_dump($_GET);
    printf("This is POST: \n");
    var_dump($_POST);
?>

我希望看到的东西 totallyRandom的变量传递给action.php,所以我可以在action.php页面上使用它。

我所看到的 另外,当我转到action.php并执行var_dump时,它返回NULL。单选按钮已通过,但未使用Axios。可以询问更多详细信息,

Picture

1 个答案:

答案 0 :(得分:2)

问题是您的<form>正在正常提交。这就是为什么看到jobtype_select POST参数而不是test的原因。

使用.prevent event modifier而非.capture

可以轻松解决此问题
<form @submit.prevent="recordTESTWo" ...

仅供参考,.capture用于...

  

针对内部元素的事件在此元素处理之前先在这里处理

这与addEventListener() useCapture 参数有关,而.prevent在事件上调用preventDefault()