使用VueJS进行POST请求提交表单

7

我有一个用POST请求提交数据的端点,

http://localhost:3000/entry

键是fname,lname,age

我可以向给定的端点发出POST请求,并创建一个条目。

我正在尝试使用VueJS提交表单。但是,当我在表单中调用API时,它不会提交数据。我已经检查了网络调用,它没有向端点发送任何数据。

HTML :-

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.16/vue-resource.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">


<div id="vueApp">
  <div class="container">

    <div class="row">
      <div class="col-sm-12">
        <h3>
          Dashboard
        </h3>
      </div>
    </div> 

    <div class="row">
      <div class="col-sm-12">
        <div class="form-group">
          <label for="fname">First Name</label>
          <input type="text" class="form-control" value="" v-model="fname" />
        </div>
        <div class="form-group">
          <label for="lname">Last Name</label>
          <input type="text" class="form-control" value="" v-model="lname" />
        </div>
        <div class="form-group">
          <label for="age">Age</label>
          <input type="text" class="form-control" value="" v-model="age" />
        </div>
      </div>
      <div class="col-sm-12">
        <a href="#" class="btn btn-success" @click="submitEntry">Submit</a>
        <span v-if="ajaxRequest">Please Wait ...</span>
      </div>
    </div> 

    <div>&nbsp;</div>

    <div class="row" v-if="debug">
      <div class="col-sm-12">
        <pre>{{ $data | json }}</pre>
      </div>
    </div>

    <!-- Table Start -->

    <div class="row">
      <table style="width:100%">
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Age</th>
        </tr>
        <tr>
          <td>{{fname}}</td>
          <td>{{lname}}</td>
          <td>{{age}}</td>
        </tr>
      </table>
    </div>
    <!-- Table END -->

  </div>
</div>

script.js :-

Vue.http.options.emulateJSON = true;

new Vue({
    el: '#vueApp',
    data: {
        debug: true,
        fname: '',
        lname: '',
        age: '',
        ajaxRequest: false,
        postResults: []
    },
    methods: {
      submitEntry: function() {
        this.ajaxRequest = true;
        this.$http.post('http://localhost:3000/entry', {
              fname: this.fname,
              lname: this.lname,
              age: this.age
            }, function (data, status, request) {
                this.postResults = data;

                this.ajaxRequest = false;
            });
      }}
});

style.css :-

table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;    
}

1
你的控制台有没有出现任何错误? - Jim Wright
1
你可能想尝试使用@click.prevent,同时在submitEntry()函数内添加一个console.log来查看它是否被调用。 - Jim Wright
1
@DineshAhuja 你是什么意思?没有服务器?像 file:///......./index.html 这样吗?那么 AJAX 就无法工作。 - user5734311
请在http Ajax请求内部发布console.log(this.fname)的结果。 - Enrico
你的.post处理程序不是一个箭头函数(x=>...),因此在其中“this”未绑定(或绑定到错误的对象)。 - birdspider
显示剩余5条评论
3个回答

4
你可以试试这个。
axios.post('http://localhost:3000/entry',{ params: { fname: this.fname, lname: this.lname, age: this.age }})
.then(response => this.responseData = response.data)
.catch(error => {});

在使用之前,您需要链接 Axios CDN。

https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js


2
尽管这有点老,但我遇到了同样的问题,即没有数据发送到端点(并且此问题在Google中排名第一)。问题在于vue-resource的$http.post()默认将数据发布为resource/json而不是表单。要发布表单,请将emulateJSON设置为true,它会将“请求体作为application/x-www-form-urlencoded内容类型”发送。
另外,结果是Promise,这意味着应该使用then()来处理响应(正如@ribas所正确提到的)。
因此,上面示例中的submitEntry()应该是:
      submitEntry: function() {
        this.ajaxRequest = true;
        this.$http.post('http://localhost:3000/entry', {
            fname: this.fname,
            lname: this.lname,
            age: this.age
          }, {
            emulateJSON: true  // <-- This was missing
          }).then(function (data) {  // <-- Handle results like this
            this.postResults = data;
            this.ajaxRequest = false;
          });
      }}

使用完全不同的库(axios)是可以的,实际上Vue的创建者Evan You也推荐使用它,但这并不能解决使用vue-resource ajax库时遇到的实际问题。

0

或许是这样

this.$http({method: 'POST', url: URL, data: data})
.then(response => {
   this.postResults = data;
   this.ajaxRequest = false;
}).catch((err) => {
  console.log(err)
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接