簡體   English   中英

無法使用vue.js和Ajax將JSON數據發布到Rest API

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

使用ajax和vue.js,我能夠從創建的api獲取並顯示數據。 但是,當我嘗試發布到api時,遇到了問題。 控制台中什么都沒有顯示,所以這個問題對我來說尤其復雜。 當我在函數內修改警報時,表單中的數據綁定似乎正在起作用並傳遞到函數中。 但是,沒有數據正在發送。

這是我的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>

這是newGuest的數據設置,它是綁定到表單輸入字段的json:

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

最后,這是用於發送帖子請求的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 = ''

  }

我的使用ajax的get請求看起來幾乎完全相同,並且可以正常工作。 所以我很確定我的ajax語法是正確的

您應該使用vue-resource ,它專門用於VueJS。 您將不會遇到現在遇到的問題,並且該功能與jQuery的AJAX函數非常相似:

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

文檔在這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM