ajax、fecth、axios

224 阅读2分钟

原生ajax

var xhr = new XMLHttpRequest()
// 必须在调用 open()之前指定 onreadystatechange 事件处理程序才能确保跨浏览器兼容性
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 300 || xhr.status ==== 304) {
      console.log(xhr.responseText)
    } else {
      console.log('Error:' + xhr.status)
    }
  }
}
// 第三个参数表示异步发送请求
xhr.open('get', '/api/getSth',  true)
// 参数为作为请求主体发送的数据
xhr.send(null)

readyState

  • 0 未初始化。尚未调用 open()方法。
  • 1 启动。已经调用 open()方法,但尚未调用 send()方法。
  • 2 发送。已经调用 send()方法,但尚未接收到响应。
  • 3 接收。已经接收到部分响应数据。
  • 4 完成。已经接收到全部响应数据,而且已经可以在客户端使用了。

jquery封装ajax

$.ajax({
    type:'POST',//默认GET
    url: url,//请求地址
    dataType: 'json', // 设置返回值类型
    contentType: 'application/json', // 设置参数类型
    headers: {'Content-Type','application/json'},// 设置请求头
    xhrFields: { withCredentials: true }, // 跨域携带cookie
    data: JSON.stringify({a: [{b:1, a:1}]}), // 传递参数
    error:function(xhr,status){  // 错误处理
       console.log(xhr,status);
    },
    success: function (data,status) {  // 获取结果
       console.log(data,status);
    }
})

fetch

const options = {
    method: "POST", // 请求参数
    headers: { "Content-Type": "application/json"}, // 设置请求头
    body: JSON.stringify({name:'123'}), // 请求参数
    credentials: "same-origin", // cookie设置
    mode: "cors", // 跨域
}
fetch('http://www.xxx.com',options)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson); // 响应数据
  })
  .catch(function(err){
    console.log(err); // 异常处理
  })

axios

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

跨域

nginx反向代理

cors

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    next();
});

jsonp

postMessage

//捕获iframe
var domain = 'http://scriptandstyle.com';
var iframe = document.getElementById('myIFrame').contentWindow;

//发送消息
setInterval(function(){
	var message = 'Hello!  The time is: ' + (new Date().getTime());
	console.log('blog.local:  sending message:  ' + message);
        //send the message and target URI
	iframe.postMessage(message,domain); 
},6000);
//响应事件
window.addEventListener('message',function(event) {
	if(event.origin !== 'http://davidwalsh.name') return;
	console.log('message received:  ' + event.data,event);
	event.source.postMessage('holla back youngin!',event.origin);
},false);

WebSocket

 function WebSocketTest(){
    if ("WebSocket" in window){
       alert("您的浏览器支持 WebSocket!");
       // 打开一个 web socket
       var ws = new WebSocket("ws://localhost:3000/abcd");
       ws.onopen = function(){
          // Web Socket 已连接上,使用 send() 方法发送数据
          ws.send("发送数据");
          alert("数据发送中...");
       };
       ws.onmessage = function (evt) { 
          var received_msg = evt.data;
          alert("数据已接收...");
       };
       ws.onclose = function(){ 
          // 关闭 websocket
          alert("连接已关闭..."); 
       };
    } else{
       // 浏览器不支持 WebSocket
       alert("您的浏览器不支持 WebSocket!");
    }
 }