如何和后端交互
- form 表單提交
- ajax
- websocket
什么是ajax
ajax是一種技術(shù)方案牛哺,但并不是一種新技術(shù)漱受。它依賴的是現(xiàn)有的CSS/HTML/Javascript,而其中最核心的依賴是瀏覽器提供的XMLHttpRequest對(duì)象潘鲫,是這個(gè)對(duì)象使得瀏覽器可以發(fā)出HTTP請(qǐng)求與接收HTTP響應(yīng)。 實(shí)現(xiàn)在頁(yè)面不刷新的情況下和服務(wù)端進(jìn)行數(shù)據(jù)交互
怎么實(shí)現(xiàn)
- XMLHttpRequest對(duì)象
- fetch 兼容性
范例
寫(xiě)一個(gè) ajax
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://api.jirengu.com/weather.php', true)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4) {
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
//成功了
console.log(xhr.responseText)
} else {
console.log('服務(wù)器異常')
}
}
}
xhr.onerror = function(){
console.log('服務(wù)器異常')
}
xhr.send()
換種寫(xiě)法
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://api.jirengu.com/weather.php', true)
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
//成功了
console.log(xhr.responseText)
} else {
console.log('服務(wù)器異常')
}
}
xhr.onerror = function(){
console.log('服務(wù)器異常')
}
xhr.send()
post的使用
var xhr = new XMLHttpRequest()
xhr.timeout = 3000 //可選,設(shè)置xhr請(qǐng)求的超時(shí)時(shí)間
xhr.open('POST', '/register', true)
xhr.onload = function(e) {
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
console.log(this.responseText)
}
}
//可選
xhr.ontimeout = function(e) {
console.log('請(qǐng)求超時(shí)')
}
//可選
xhr.onerror = function(e) {
console.log('連接失敗')
}
//可選
xhr.upload.onprogress = function(e) {
//如果是上傳文件怎爵,可以獲取上傳進(jìn)度
}
xhr.send('username=jirengu&password=123456')
封裝一個(gè) ajax
function ajax(opts){
var url = opts.url
var type = opts.type || 'GET'
var dataType = opts.dataType || 'json'
var onsuccess = opts.onsuccess || function(){}
var onerror = opts.onerror || function(){}
var data = opts.data || {}
var dataStr = []
for(var key in data){
dataStr.push(key + '=' + data[key])
}
dataStr = dataStr.join('&')
if(type === 'GET'){
url += '?' + dataStr
}
var xhr = new XMLHttpRequest()
xhr.open(type, url, true)
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
//成功了
if(dataType === 'json'){
onsuccess( JSON.parse(xhr.responseText))
}else{
onsuccess( xhr.responseText)
}
} else {
onerror()
}
}
xhr.onerror = onerror
if(type === 'POST'){
xhr.send(dataStr)
}else{
xhr.send()
}
}
ajax({
url: 'http://api.jirengu.com/weather.php',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret)
},
onerror: function(){
console.log('服務(wù)器異常')
}
})