te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Submit a form using POST request in VueJS - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Submit a form using POST request in VueJS - Stack Overflow

programmeradmin1浏览0评论

I have an endpoint to submit data using POST request,

http://localhost:3000/entry

Keys are fname, lname, age

I can make a POST request into the given end point and it will create an entry.

I am trying to submit a form using VueJS. But, when I am calling the API within the form, it is not submitting the data. I have checked the network calls and it is not sending any data to the end point.

HTML :-

<script src=".0.4/vue.min.js"></script>
<script src=".1.16/vue-resource.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href=".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;    
}

I have an endpoint to submit data using POST request,

http://localhost:3000/entry

Keys are fname, lname, age

I can make a POST request into the given end point and it will create an entry.

I am trying to submit a form using VueJS. But, when I am calling the API within the form, it is not submitting the data. I have checked the network calls and it is not sending any data to the end point.

HTML :-

<script src="https://cdnjs.cloudflare./ajax/libs/vue/1.0.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare./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./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;    
}
Share Improve this question asked Jul 19, 2018 at 11:16 Dinesh AhujaDinesh Ahuja 1,0253 gold badges18 silver badges29 bronze badges 10
  • 1 Are you getting any errors in your console? – Jim Wright Commented Jul 19, 2018 at 11:21
  • No, no error is showing. – Dinesh Ahuja Commented Jul 19, 2018 at 11:23
  • 1 You might want to try @click.prevent, also add a console.log inside of submitEntry() to see if it is being called. – Jim Wright Commented Jul 19, 2018 at 11:24
  • Putting the above in a fiddle, I first get an error that a request to http is blocked from a https context. When I change it to https, I get a CORS error, as expected. Is the Vue app served from localhost:3000, too? – user5734311 Commented Jul 19, 2018 at 11:25
  • 1 @DineshAhuja How do you mean? Without a server? Like file:///......./index.html? Then AJAX won't work. – user5734311 Commented Jul 19, 2018 at 11:37
 |  Show 5 more ments

3 Answers 3

Reset to default 4

You can try this one.

axios.post('http://localhost:3000/entry',{ params: { fname: this.fname, lname: this.lname, age: this.age }})
.then(response => this.responseData = response.data)
.catch(error => {});

Before using you need to link with Axios CDN

https://cdn.jsdelivr/npm/[email protected]/dist/axios.min.js

Even though this is a bit old, I just ran into this same issue where no data was sent to the endpoint (and this question es up first in Google). The problem is that vue-resource's $http.post() defaults to posting data as resource/json and not a form. To post a form, set emulateJSON to true which will send the "request body as application/x-www-form-urlencoded content type".

As an aside, the result is a Promise, which means then() should be used to handle the response (as @ribas correctly mentioned).

So the submitEntry() in the example above should be:

      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;
          });
      }}

Using a pletely different library (axios) is fine and actually remended by Evan You (creator of Vue), but it doesn't address the actual problem using the vue-resource ajax library.

Maybe something like this

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

评论列表(0)

  1. 暂无评论