原生ajax
var xhr = new XMLHttpRequest()
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',
url: url,
dataType: 'json',
contentType: 'application/json',
headers: {'Content-Type','application/json'},
xhrFields: { withCredentials: true },
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",
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
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);
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!");
var ws = new WebSocket("ws://localhost:3000/abcd");
ws.onopen = function(){
ws.send("发送数据");
alert("数据发送中...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("数据已接收...");
};
ws.onclose = function(){
alert("连接已关闭...");
};
} else{
alert("您的浏览器不支持 WebSocket!");
}
}