1. 程式人生 > >vue 添加axios解決post傳參數為null問題

vue 添加axios解決post傳參數為null問題

ams 問題 null new sea 添加 mark resp then

本文主要參考:

https://www.npmjs.com/package/axios

http://jingyan.baidu.com/article/29697b916d6a7bab20de3cf9.html

好,下面上貨。

1、安裝axios

npm install axios --save

2、添加axios組件

import axios from ‘axios‘
axios.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded‘;
axios.defaults.baseURL = ‘http://localhost:7878/zkview‘;
Vue.prototype.$ajax = axios;

3、get請求

testGet: function () {
  this.$ajax({
    method: ‘get‘,
    url: ‘/test/greeting‘,
    params: {
      firstName: ‘Fred‘,
      lastName: ‘Flintstone‘
    }
  }).then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  });
},

4、post請求

testPost: function () {
        var params = new URLSearchParams();
        params.append(‘name‘, ‘hello jdmc你好‘);
        params.append(‘id‘, ‘2‘);
        this.$ajax({
          method: ‘post‘,
          url: ‘/test/greeting2‘,
          data:params
//          data: {id: ‘3‘, name: ‘abc‘}
}).then(function (response) {
          console.log(response);
        }).catch(function (error) {
          console.log(error);
        })
      }

5、運行結果:

技術分享圖片

技術分享圖片

6、註意:

在使用post方式的時候傳遞參數有兩種方式,一種是普通方式,一種是json方式,如果後臺接受的是普通方式,那麽使用上述方式即可。

普通的formed方式

var params = new URLSearchParams();
params.append(‘name‘, ‘hello jdmc你好‘);
params.append(‘id‘, ‘2‘);
data:params

後臺接收參數:

public Student greeting2(int id,String name) {

json方式

data: {id: ‘3‘, name: ‘abc‘}

後臺接收參數

public Object greeting2(@RequestBody Object student) {

vue 添加axios解決post傳參數為null問題