獲取跨域資料
1.fetch
window.onload=function(){
let oBtn=document.getElementById('btn');
oBtn.onclick=async function(){
//請求資料
let res=await fetch('data/1.txt');
//解析資料
let str=await res.text();
console.log(str);
}
}
2.formdata
$('#form1').on('submit', function () {
let formdata = new FormData(this);
$.ajax({
url: this.action,
type: this.method,
data: formdata,
processData: false,
contentType: false
}).then(data => {
console.log('success');
}, err => {
console.log('fail');
});
return false;
});
3.websocket
<script>
let sock = io.connect('ws://localhost:8080/');
//給server發訊息
//sock.emit('aaa', 12, 5);
//接收server的訊息
sock.on('timer', function (time) {
console.log(time);
})
</script>
server端
const http = require('http');
const io = require('socket.io');
//建立http
let server = http.createServer((req, res) => {});
server.listen(8080);
//建立websocket
let wsServer = io.listen(server);
wsServer.on('connection', sock => {
//接收前端發來的資料
// sock.on('aaa', function (a, b) {
// console.log(a, b, a + b);
// });
//前端也可以傳送訊息
setInterval(function () {
sock.emit('timer', new Date().getTime());
}, 2000);
});
4. Jsonp
$(function(){
let oTxt=document.getElementById('txt');
$('#txt').on('input',function(){
$.ajax({
url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
data:{wd:$(this).val()},
dataType:'jsonp', //只有格式是JsonP才可以跨域
jsonp:'cb'
}).then((data)=>{
//ajax 也是一個promise,它成功之後執行resolve,這個resolve就是then裡面的第一個函式
console.log('####'+data.s);
},res=>{
console.log('shibai');
});
});
});