1 ajax全称:Asynchronous JavaScript and XML
异步javascript和xml,作用:允许浏览器与服务器通信而无须刷新当前页面的技术,即局部刷新
jQuery 中的 Ajax
jQuery 对 Ajax 操作进行了封装, 在 jQuery 中最底层的方法时 $.ajax(), 第二层是 load(), $.get() 和 $.post(), 第三层是 $.getScript() 和 $.getJSON()
$.ajax使用
$(function(){$('#send').click(function(){
$.ajax({
type: "GET", //类型
url: "test.json",//接收的地址
data: {username:$("#username").val(), content:$("#content").val()},//传送的数据,
dataType: "json",//传送的数据类型
success: function(data){$('#resText').empty(); //清空resText里面的所有内容
var html = '';$.each(data, function(commentIndex, comment){
html += '<div class="comment"><h6>'+ comment['username']+ ':</h6><p class="para"' + comment['content']+ '</p></div>';});$('#resText').html(html);}
});
});
});
注:如果要传送整个表单中内容:可以用$("#form的id名").serialize()
即:data:$("#form1").serialize(),要求表单中元素要有名,服务端才能取
<form id="form1" method="post">
$.ajax({
type:"post",//发送类型
url:"LoginServlet",//接收地址
data:$("#form1").serialize(),//{"name":name,"pwd":pwd},//将要传送的数据
//serialize()表示表单中所有
dataType:"text",//传送的数据类型,不写自动识别
success:function(msg){//成功后的回调
alert("服务器回调信息为:"+msg)
if(msg==0){
alert("用户名或密码不符!!");
}else{
alert("合法用户!!");
location="main.jsp";
}
}
}) //位置没有固定顺序
$.post使用
1 $.post(url, [data], [callback], [type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
注:位置不能改变
$.post(
"LoginServlet",//接收地址
{"name":name,"pwd":pwd},//将要传送的数据
//$("#form1").serialize()表示表单中所有
function(msg){//成功后的回调
alert("服务器回调信息为:"+msg)
if(msg==0){
alert("用户名或密码不符!!");
}else{
alert("合法用户!!");
location="main.jsp";
}
},"text"
)
注:text也可以不写,将自动适应
$.get使用
1 $.get(url, [data], [callback], [type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
注:位置不能改变