@Secretmm
2018-03-15T10:17:17.000000Z
字数 2266
阅读 794
web前端
https://segmentfault.com/a/1190000004322487
事件是被动触发,方法是主动调用
XMLHttpRequest发送Ajax请求的简单示例
function sendAjax(url) {
var formData = new FormData();
formData.append('name', 'zmm');
formData.append('id', '3662');
var xhr = new XMLHttpRequest();
xhr.timeout = 3000;
//用于传输数据【方法】
xhr.open('GET', url, true);
//传输成功完成【事件】
xhr.onload = function() {
var data = JSON.parse(xhr.response);
if(data.code === 0) {
console.log('hhh');
} else {
alert(data.data);
}
}
//传输超时【事件】
xhr.ontimeout = function(e) {
alert('请求已超时!');
}
//相当于[其他事件也是如此]
xhr.addEventListener('timeout',function(e) {
alert('请求已超时!');
});
//传输出现错误【事件】
xhr.onerror = function(e) {
alert('数据加载失败,请重试!');
}
//上传进度信息【事件】
xhr.upload.onprogress = function(e) {
var percent = 1;
//e.lengthComputable不为真时,e.total为0
if(e.lengthComputable) {
//e.loaded已经传输的字节, e.total传输总字节
percent = e.loaded / e.total;
}
};
//下载进度信息【事件】
xhr.onprogress = function(e) {
var percent = 1;
if(e.lengthComputable) {
percent = e.loaded / e.total;
}
}
//发送信息【方法】
try {
xhr.send(formData);
} catch(e) {
//doSomething...
};
//传输中止【方法】
xhr.abort();
}
var xhr = new XMLHttpRequest();
xhr.open('post', 'url', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(params));
第一种:复用的模块化思想
var ajax = function(url, data, callback) {
$.ajax({
url: url,
data: data,
type:"post",
dataType: "json",
success:function(data){
if(data.code !== 0) {
alert("错误:" + data.message);
} else {
if(callback) {
callback(data);
}
}
},
error:function(){
alert("服务器提交失败,请重试。")
}
});
};
引用上面定义的ajax
one:
ajax("/api/order/create", {
id:id,
}, function(data) {
if(status==1){
window.location.href=data.data.preview_url;
} else {
window.location.reload();
}
});
});
two:
ajax("/api/teacher-assessment/teacher-assessment", {
id: id,
}, function(data) {
alert("考核评分保存成功!!");
window.location.reload();
});
第二种:直接使用;
get方法:
one:
$.ajax({
url: "/api/order/detail/?id="+id,//这个和传值id:id,是一样的
type:"get",
dataType: "json" ,
success:function(data){
if(data.code !== 0) {
alert("错误:" + data.message);
} else {
//console.log(data.data);
//console.log(data.message);
//由此判断后台传来的数据
}
},
error:function(){
alert("服务器请求失败,请重试。")
}
});
链接里传两条以上的数据:
window.location.href = '/wechat/service/choose?name='+ student_name + '&role=' + login_role +'&open=' + open;
two:
$.ajax({
url: url,
data: "WebName="+$("#WebName").val(),
type:"post",
dataType: "json",
success:function(data){
if(data.code !== 0) {
alert("错误:" + data.message);
} else {
}
},
error:function(){
alert("服务器提交失败,请重试。")
}
});