jQuery实现对ajax的封装,使代码轻量化
AJAX—$.get()
$.get()是一个简单的 GET 请求功能。请求成功时可调用回调函数。
$.get(url,[data],[callback],[type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default
注意:请求是通过 URL 提交的 提交有大小限制(2KB)
AJAX— $.post()
这是一个简单的 POST 请求功能。请求成功时可调用回调函数
$.post(url,[data],[callback],[type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default
POST 请求是 HTTP 消息实体提交的,提交大小不受限制
$("#testform").serialize() 请求发送表单数据
<script type="text/javascript">
function subform() {
//subform获得account和password打印进去的数据
var account = document.getElementById("accountId").value;
var password = document.getElementById("passwordId").value;
//使用XMLHttpRequest对象发起异步请求
var xmlHttpRequest = new XMLHttpRequest();
//建立与服务器的连接
xmlHttpRequest.open("post", "demourl", true);
//设置请求的头信息
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//设置提交数据的格式的请求头
//发送请求
xmlHttpRequest.send("account=" + account + "&password=" + password);
// 接收服务器端响应后来的数据,当发送请求之后,就会触发nreadystatechange
// 的这个事件,在此事件的回调函数中,获取响应的内容
xmlHttpRequest.onreadystatechange = function () {
//当对象就绪状态为为4,http响应状态码为200时获取响应内容
//如果不写就绪状态的话,就会获取readystate中的2,3,4依次执行一遍
//http响应就绪码,是为了确保这个响应过来的码是正确的就才能执行
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
//从后端响应回来一个json格式的字符串,在前端需要将其转换为JavaScript对象
//通过使用jQuery缩短代码量来把responseText封装为JavaScript的对象
var obj = $.parseJSON(xmlHttpRequest.responseText);
//方便前端操作
if (obj.id != null) {
alert("操作成功html");
//将对象直接存储到了当前浏览器当中
window.sessionStorage.setItem("user",xmlHttpRequest.responseText );
location.replace("success.html");//然后跳转页面来进行
} else if (xmlHttpRequest.responseText == 1){
alert("服务器忙html")
}
}
}
}
</script>
使用jQuery封装后就可以写成:
<script type="text/javascript">
function subform() {
//jQuery封装的ajax请求,post就是表示的post请求,get就表示是get请求
//$.post("demourl",{accout:$("accountId").val(),password:$("passwordId").val()});
//$("#formId").serialize() 就是将表单数据序列化 为 键=值&键=值&键=值...
//function(){} 读取到响应内容后执行
//type:json 直接将返回的json格式转为js的对象。方便前端操作
$.post("demourl", $("#formId").serialize(), function (res) {
//方便前端操作
var obj = $.parseJSON(res)
if (obj.id != null) {
alert("操作成功html");
//将对象直接存储到了当前浏览器当中
window.sessionStorage.setItem("user", res);
location.replace("success.html");//然后跳转页面来进行
} else if (obj == 1) {
alert("服务器忙html")
}
},);
}
</script>