前言: Vue的使用使前端程序员主要精力放在业务上,省去了大量dom的操作。身边的很多同事仍然使用JQuery的ajax发送请求,使用JQuery 也就仅仅使用了封装好的ajax,这样给页面的加载增加负担,JQuery的引入使页面的加载显的很笨重。前端发送请求的方式很多种,不一定要再页面上大量使用JQuery封装的ajax,有几种请求方式可以省去JQuery的引入进行ajax请求。下面我将进行一一介绍:

一.axios

首先需要知道:axios不是一种新的技术。

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范,有以下特点:

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

使用

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

get请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的请求也可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

post请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

 

二.fetch

fetch是前端发展的一种新技术产物。

使用

不需要引入js,只要引入vue.js就可以,很方便

发送请求

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

post请求传参

fetch("http://127.0.0.1:8080/getUser",
 {
	method: 'POST',
	headers: {
      'Content-Type':'application/x-www-form-urlencoded'
	},
	body:"id=39"
	})
	.then(function(resp) {
	  console.log(resp);
	return resp.json();
	})
	.then(data=>{
	console.log(data)
	that.obj=data
	})
	.catch(error=>{
	console.log(error)
	})

三.ajax

用的比较广泛的一种异步请求方式

如果没有 jQuery,AJAX 编程还是有些难度的。

编写常规的 AJAX 代码并不容易,因为不同的浏览器对 AJAX 的实现并不相同。这意味着您必须编写额外的代码对浏览器进行测试。

$.ajax({
            //请求方式
            type : "POST",
            //请求的媒体类型
            contentType: "json",
            //请求地址
            url : "http://127.0.0.1/admin/list/",
            //数据,json字符串
            data : {
             },
            //请求成功
            success : function(result) {
                console.log(result);
            },
            //请求失败,包含具体的错误信息
            error : function(e){
                console.log(e.status);
                console.log(e.responseText);
            }
        });

jQuery load()方法

jQuery load() 方法是简单但强大的 AJAX 方法。

load() 方法从服务器加载数据,并把返回的数据放入被选元素中。

语法:

$(selector).load(URL,data,callback);
$("button").click(function(){
  $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
    if(statusTxt=="success")
      alert("外部内容加载成功!");
    if(statusTxt=="error")
      alert("Error: "+xhr.status+": "+xhr.statusText);
  });
});

 

jQuery $.get() 方法

语法:

$.get(URL,callback);
$("button").click(function(){
  $.get(URL,function(data,status){
    alert("数据: " + data + "\n状态: " + status);
  });
});

jQuery $.post() 方法

语法:

$.post(URL,data,callback);
$("button").click(function(){
    $.post(URL,
    {
        name:"参数",
        url:"http://www.runoob.com"
    },
    function(data,status){
        alert("数据: \n" + data + "\n状态: " + status);
    });
});

 

四.Vue.js Ajax(vue-resource)

vue-resource是一个通过XMLHttpRequrestJSONP技术实现异步加载服务端数据的Vue插件

提供了一般的 HTTP请求接口和RESTful架构请求接口,并且提供了全局方法和VUe组件实例方法。

使用

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

get 请求

this.$http.get('/try/ajax/ajax_info.txt').then(function(res){
   document.write(res.body);    
 },function(){
   console.log('请求失败处理');
 });

如果需要传递数据,可以使用 this.$http.get('get.php',{params : jsonData}) 格式,第二个参数 jsonData 就是传到后端的数据。

this.$http.get('get.php',{params : {a:1,b:2}}).then(function(res){
    document.write(res.body);    
},function(res){
    console.log(res.status);
});

post 请求

post 发送数据到后端,需要第三个参数 {emulateJSON:true}。

emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。

this.$http.post('/try/ajax/demo_test_post.php',
{name:"参数",url:"http://www.runoob.com"},{emulateJSON:true}).then(function(res){
 document.write(res.body);    
},function(res){
  console.log(res.status);
  });