前后端数据交互的几种不同方式
前后端数据交互的几种不同方式
1、jQuery中的ajax:
实例参考:https://jquery.com/
async:Boolean类型 (true / false)
默认是true,所有请求都为异步请求 false,则所有请求为同步请求
$.ajax({
type:"Post" //提交方式
url:"/api/getWeather" //提交路径
dataType:"json",
    data:{
      zipcode:97201      //提交数据
},
headers:{a:"ajdbhabjh bv"} //请求头
success:function(result){
$("#Weather-temp").html("<strong>" + result + "</strong>")
},
error:function(xhr,status,error){ //有错误处增加error字段
console.log(error)
}
})
ajax 的过程是怎样的
1. 创建XMLHttpRequest对象,也就是创建一个异步调用对象
2. 创建一个新的HTTP请求,并指定该HTTP请求的方法、URL及验证信息
3. 设置响应HTTP请求状态变化的函数
4. 发送HTTP请求
5. 获取异步调用返回的数据
6. 使用JavaScript和DOM实现局部刷新
2、jquery ajax 获取数据 转换成 Json:
$(function(){
    		  var val="";
    		  $.post("book_findBooksJson.action",function(data){
    			    $.each(data,function(index,content){
   					      for(var i=0;i<content.length;i++){
   						        val="<tr><td>"+content[i].id+"</td><td>"+content[i].name+"</td><td>"+content[i].user.username+"</td></tr>";
   						      $("#table tbody").append(val);
   					      }
    			    });  
    		  },"json");
    	});
3、fetch方法
fetch的post表单数据用法:
fetch("http://localhost:99", {
  method:"Post",
  data:{a:11},
  headers:{"content-type": "appliceation/json"
}
  body:JSON.stringify({ 
a:1
})
})
.then(res=>res.json())
.then(d=>console.log(d))
.catch(e=>{})
4、axios方法
// axios默认是json类型的提交
axios({
  url:'http://localhost:99',
  method:"POST",
  data:{
a:12
},
}).then(res=>{console.log(res.data)})
// 如果想改成from则需要修改header和data格式
axios({
  url:'http://localhost:99',
  method:"POST",
  data:{a:12},
  headers:{a:dafdsafds}
}).then(res=>{
console.log(res.data)
})
以上仅限于个人总结,仅作交流学习。
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号