一、原生js-ajax
1.xmlhttp
*属性
*readyState: 状态
*0 : xmlhttp对象创建
*1 :调用了open方法
*2 :调用了send方法
*3 :部分相应
*4 :完全相应
* onreadystatechange : function() //当状态发生改变时,会调用该函数
* responseText //从服务器响应过来的数据
* status
* 方法
* open : 打开一条路径 : 指定 url
* send : 发送ajax请求
* setRequestHeader : post 参数使用的!!
2. 步骤
1. 创建 xmlhttp 对象
2. 指定回调函数 :
2.1. xmlhttp.onreadystatechange = fn
3. open: 指定请求方式,请求路径
4. send: 发送ajax
Get请求发送ajax (中文有乱码)
<script type=”text/javascript”>
//一、创建xmlhttp对象
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//二、指定回调函数
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var text = mlhttp.responseText;
alert(text);
}
}
//三、指定请求路径
xmlhttp.open(“method请求方式”,url+参数);
//四.发送ajax
xmlhttp.send();
</script>
二、POST请求发送ajax
<script type=”text/javascript”>
//一、创建xmlhttp对象
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//二、指定回调函数
xmlhttp.onreadystatechange = function(){
f(xmlhttp.readyState==4 && xmlhttp.status==200){
var text = mlhttp.responseText;
alert(text);
}
}
//三、指定请求路径
xmlhttp.open(“method请求方式”,url);
xmlhttp.setRequestHeader(content-type","application/x-www-form-urlencoded");
//四.发送ajax
方式一:
xmlhttp.send(“username”=+username);
方式二:
var para = “username”=+username
xmlhttp.send(para);
</script>
三、jquery-ajax
1. $.ajax(js对象);
2. $.get(url,data,fn,type);
3. $.post(url,data,fn,type);
4. $.load(js对象);
3.1#$.ajax#
1. type 请求方式
2. url 请求路径
3. dataType 服务器返回类型
1. text
2. json
4. success : fn 回调函数
5. data :请求携带到服务器的参数
1. data: "name=John&location=Boston",
3.2jquery-get请求发送ajax (中文有乱码)
function sendUsername(u){
var username = u.value;
$.ajax({
type: "GET",
url:"${pageContext.request.contextPath }/Test2UsernameServlet",
dataType: "json",
data : "username="+username,
success: function(data){ //在完全响应的时候才会调用
//data.username
alert("服务器响应数据==="+ data);
}
});
}
3.3jquery-post请求发送ajax,只需把type中的get改成post就行。
四、bootstrapValidator-get请求验证 (中文有乱码)
//远程验证
remote: {
type:'GET',
url:'${ctx}/UserServlet?method=checkUsername',
message:'该用户名已被占用'
}
直接把远程验证放到要发送ajax的js对象中。
例如:用户名要进行ajax验证请求