mui框架基于htm5plus的XMLHttpRequest,封装了常用的Ajax函数,支持GET、POST请求方式,支持返回json、xml、html、text、script数据类型; 本着极简的设计原则,mui提供了mui.ajax方法,并在mui.ajax方法基础上,进一步简化出最常用的mui.get()、mui.getJSON()、mui.post()三个方法。
mui.ajax()
mui.ajax('http://server-name/login.php',{
data:{
username:'username',
password:'password'
},
dataType:'json',//服务器返回json格式数据
type:'post',//HTTP请求类型
timeout:10000,//超时时间设置为10秒;
headers:{'Content-Type':'application/json'},
success:function(data){
//服务器返回响应,根据响应结果,分析是否登录成功;
...
},
error:function(xhr,type,errorThrown){
//异常处理;
console.log(type);
}
});
mui.post()
mui.post('http://server-name/login.php',{
username:'username',
password:'password'
},function(data){
//服务器返回响应,根据响应结果,分析是否登录成功;
...
},'json'
);
mui.get()
mui.get('http://server-name/list.php',{category:'news'},function(data){
//获得服务器响应
...
},'json'
);
封装 AJax
通常在项目中,我们并不会直接使用它,而是会封装一下。
// **.js 请求数据
function startRequest(url, callBack) {
//接口地址
var GETURL = "https://www.easy-mock.com/mock/5cae89ce96ef6f08c01d52de/fitness/" + url;
mui.ajax(GETURL, {
dataType: 'json', //服务器返回json格式数据
type: 'get', //HTTP请求类型
success: function(data) {
console.log(data);
callBack(data); //回调函数
},
error: function(xhr, type, errorThrown) {
console.log(type);
return "网络错误";
}
});
}
var HTTP_ACTION = {
//请求用户名密码
userccount: function(callBack) {
startRequest("userccount", callBack);
}
}
**.html 调用请求数据
//请求用户名密码
HTTP_ACTION.userccount(function(data){
console.log(data);
});