ajax指的是在不刷新页面的情况下发送的网络请求,即异步请求。
在js中的写法:
var xmlHttpReq=null;//声明一个空对象用来装入XMLHttpRequest对象function sendAjax(){ ???if(window.XMLHttpRequest){ //除IE5,6以外的浏览器 ???????xmlHttpReq=new XMLHttpRequest(); ???}else{ ?//IE5,6是以ActiveXObject的方式引入XMLHTTPRequest对象的 ???????xmlHttpReq=new ActiveXObject(‘Microsoft.XMLHTTP‘); ???} ???xmlHttpReq.open(‘GET‘,‘test.php‘,true); ???xmlHttpReq.onreadystatechange=function(){ ???????if(xmlHttpReq.readyState===4){ ???????if(xmlHttpReq.status===200){ ???????????????????????document.getElementById(‘resText‘).innerHTML=xmlHttpReq.responseText; ???????} ???????} ???} ???xmlHttpReq.send();}
在Jquery中,将ajax请求的细节进行了封装,提供了ajax、get、post等方法。
$.ajax()
1 $.ajax({2 ????????????url:‘text.php‘,3 ????????????type:‘GET/POST‘,//请求方式4 ????????????data:‘‘,//发送到服务器的数据,若是get请求则将附加在url后5 ????????????dataType:‘json‘,//预期服务器返回的数据类型6 ????????????success:function(){},//请求成功的回调函数7 ????????????error:function(){}//请求失败的回调函数8 ????????});
$.get()
1 $.get(url,[,data][,callback][,type]);2 3 $(‘#send‘).click(function(){4 ????$.get(‘get1.php‘,{5 ????????username:$(‘#username‘).val(),6 ????????content:$(‘#content‘).val()7 ????},function(data,textStatus){/*回调处理*/});8 });
$.post()与$.get()结构和使用方式都相同
1 $(‘#send‘).click(function(){2 ????$.post(‘get1.php‘,{3 ????????username:$(‘#username‘).val(),4 ????????content:$(‘#content‘).val()5 ????},function(data,textStatus){ ?//data表示响应的数据,textStatus表示响应的状态6 ????????/*回调处理*/7 ????});8 });
但是post请求和get请求还是有很大的区别:
1.get请求会将参数放在url后,而post请求不会,post请求安全性更高。
2.get请求对传输的数据大小有限制,post请求理论上没有限制。
3.get请求的数据会被浏览器缓存起来。
ajax的写法
原文地址:https://www.cnblogs.com/cherryshuang/p/8489530.html