简体   繁体   English

无法使用vue.js和Ajax将JSON数据发布到Rest API

[英]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. 使用ajax和vue.js,我能够从创建的api获取并显示数据。 However, when I try posting to the api, I run into issues. 但是,当我尝试发布到api时,遇到了问题。 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 : 这是我的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的数据设置,它是绑定到表单输入字段的json:

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

finally, here is the vue.js/ajax code for sending post request: 最后,这是用于发送帖子请求的vue.js / ajax代码:

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. 我的使用ajax的get请求看起来几乎完全相同,并且可以正常工作。 So im pretty sure my ajax syntax is correct 所以我很确定我的ajax语法是正确的

You should use vue-resource , which is designed to work specifically with VueJS. 您应该使用vue-resource ,它专门用于VueJS。 You won't have the problems that you have now and the functionality is pretty similar to jQuery's AJAX functions: 您将不会遇到现在遇到的问题,并且该功能与jQuery的AJAX函数非常相似:

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

Docs here. 文档在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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