ajax是什么,怎么用法?
- ajax即“Asynchronous javascript and xml”(异步JavaScript和xml),其实是我们去操纵xml httprequest这个对象,向后台要数据,这个对象要完数据之后,页面不刷新,我们直接拿到这个数据然后进行一些展示或者处理。
如何mock数据?
- 使用http-server打开一个静态服务器,在git bash 中输入
http-server
运行服务器,并使用该地址来访问相关文件。 - 使用线上平台来mock数据。比如
https://easy-mock.com
这种平台 - 使用git hub 来实现mock数据,具体是将code传入gitpage来实现预览
- 使用node.js来手写一个静态服务器。
用代码区分使用post和get两种方法时在使用ajax的不同
- 使用GET方法时(默认使用该方法)
<script>
var xhr = new XMLHttpRequest()
xhr.open('GET', '/hello.json',true)
xhr.send()
xhr.onload = function(){
if( (xhr.status >=200 && xhr.status <300) || xhr.status === 304){
var data = xhr.responseText
console.log(data)
}
else{
console.log('error')
}
}
</script>
- 使用post方法
<script>
var xhr = new XMLHttpRequest()
xhr.open('POST', '/hello',true)
xhr.send('name=jirengu$age=2')
xhr.onload = function(){
if( (xhr.status >=200 && xhr.status <300) || xhr.status === 304){
var data = xhr.responseText
console.log(data)
}
else{
console.log('error')
}
}
</script>
封装一个 ajax 函数,能实现如下方法调用
function ajax(options){
//补全
}
ajax({
url: 'http://api.jirengu.com/weather.php',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret)
},
onerror: function(){
console.log('服务器异常')
}
})
答案
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 += url+'?'+ dataStr
}
var xhr = new XMLHttpRequest()
xhr.open(type,url,true)
xhr.onload = function(){
if ((xhr.status >=200 && xhr.statue <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 : 'https://jirengu.com',
data : {
city: "北京"
},
onsuccess:function(ret){
console.log(ret)
},
onerror : function(){
console.log('服务器异常')
}
})
网友评论