vue中get和post請求


 

現在

vue中和后台交互,首先要引用vue-resource.js

vue-resource.js是專門和后台進行交互

<!-- ==============引入vue-resource插=================--> 
<script src="../js/vueJs/vue-resource.js"></script>

 

 

vue的get請求

function getRequest(url, params) {
  return new Promise((resolve, reject) => {
    Vue.$http.get(
      url,
      {
        params: params
      },
      {emulateJSON: true}
    )
    .then((res) => {   //成功的回調
      resolve(res);
    })
    .catch((res) => {  //失敗的回調
      reject(res);
    });
  });
}

vue的get請求傳遞參數的時候要用{params:{id:'1'}},這樣來傳遞參數,否則就無法傳遞參數

 

vue的post請求

function postRequest(url, params) {
  return new Promise((resolve, reject) => {
    Vue.$http.post(
      url,
      {
        params
      },
      {emulateJSON: true}
    )
    .then((res) => {    //成功胡回調
      resolve(res.body);
    })
    .catch((res) => {   //失敗的回掉
      reject(res.body);
    });
  });
}

 

 

例子--

methods: {
    research: function () {
        //post請求遠程資源
        this.$http.post(
            //請求的url
            "http://www.hefeixyh.com/login.html",
            //請求參數,不能以get請求方式寫:{params: {userName: "root123", passWord: "root123"}}
            {userName: "root123", passWord: "root123"},
            //解決跨域問題,不加無法跨域
            {emulateJSON: true}
        ).then(
            function (res) {
                console.log(res);
                this.msg = res.bodyText;
            },
            function (res) {
                console.log(res.status);
            }
        );
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM