简体   繁体   中英

unable to post json data to rest api using vue.js and ajax

Using ajax and vue.js, i was able to get and display data from an api i created. However, when I try posting to the api, I run into issues. Nothing is showing up in the console, so this issue is particularly complicated for me. The data binding in my form appears to be working and passing into the function when i tinker with alerts within the function. however, no data is being sent.

here is my html :

<form>

  <input placeholder="Enter your Name" v-model="newGuest.name"><br><br>

  <textarea placeholder="Leave a Message" v-model="newGuest.message"></textarea><br><br>

  <button v-on:click="addGuest">Submit</button>

</form>

here is the data setup for newGuest, which is the json binded to the form input fields:

newGuest: {
    name:'',
    message:''
  }

finally, here is the vue.js/ajax code for sending post request:

addGuest: function () {

    var xhp = new XMLHttpRequest()
    xhp.open('POST', apiURL)
    xhp.setRequestHeader("Content-type", "application/json");
    xhp.send(this.newGuest)

    this.newGuest.name = ''
    this.newGuest.message = ''

  }

my get requests using ajax look almost exactly the same, and it is working. So im pretty sure my ajax syntax is correct

You should use vue-resource , which is designed to work specifically with VueJS. You won't have the problems that you have now and the functionality is pretty similar to jQuery's AJAX functions:

  this.$http({url: '/someUrl', method: 'GET'}).then(function (response) {
      // success callback
  }, function (response) {
      // error callback
  });

Docs here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM