1.ajax 是什么筒捺?有什么作用
Asynchronous JavaScript + XML(異步JavaScript和XML), 其本身不是一種新技術(shù),而是一個(gè)在 2005年被Jesse James Garrett提出的新術(shù)語(yǔ)冯挎,用來(lái)描述一種使用現(xiàn)有技術(shù)集合的‘新’方法,包括: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, 以及最重要的 XMLHttpRequest object咙鞍。當(dāng)使用結(jié)合了這些技術(shù)的AJAX模型以后房官, 網(wǎng)頁(yè)應(yīng)用能夠快速地將增量更新呈現(xiàn)在用戶(hù)界面上趾徽,而不需要重載(刷新)整個(gè)頁(yè)面。這使得程序能夠更快地回應(yīng)用戶(hù)的操作翰守。
2.如何 mock 數(shù)據(jù)孵奶?
1.安裝Node.js ,通過(guò)http-server開(kāi)啟本地服務(wù)器
獲取端口http://localhost:8000
然后通過(guò)在文件夾創(chuàng)建html和json文件來(lái)測(cè)試數(shù)據(jù)
2.通過(guò)線(xiàn)上來(lái)mock數(shù)據(jù)
使用 https://easy-mock.com
使用 http://rapapi.org/org/index.do
3.GET 和 POST 類(lèi)型的 ajax 的用法
xhr.open('GTE','/login?username=abc&password=123',true)
xhr.onload= function(){
if(xhr.status>=200 && xhr.status<300 || xhr.status=304){
console.log(xhr.responseText)
}else {
console.log('服務(wù)器出錯(cuò)蜡峰!')
}
}
xhr.onerror= function(){
console.log('服務(wù)器出錯(cuò)了袁!')
}
xhr.send() //GET的用法,拼接的數(shù)據(jù)放在open的第二個(gè)參數(shù)中
var xhr= new XMLHttpRequest()
xhr.timeout= 1000
xhr.open('POST','/login',true)
xhr.addEventListener('load',function(){
if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
var data=xhr.requestText
console.log(data)
}else {
console.log('服務(wù)器儲(chǔ)出錯(cuò)湿颅!')
}
})
xhr.ontimeout= function(){
console.log('請(qǐng)求超時(shí)')
}
xhr.onerror= function(){
console.log('服務(wù)器出錯(cuò)载绿!')
}
xhr.send('usernsme=abc&password=123')
//POST的用法,數(shù)據(jù)需放在send中
4.封裝一個(gè) ajax 函數(shù)油航,能實(shí)現(xiàn)如下方法調(diào)用
function ajax(options){
//補(bǔ)全
}
ajax({
url: 'http://api.jirengu.com/weather.php',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret)
},
onerror: function(){
console.log('服務(wù)器異常')
}
})
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()
}
}