使用jQuery实现异步操作,可以简化开发。
使用jQuery要引入包
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
ajax格式:
$.ajax({
url:服务器地址,
type;get|post,
data:请求数据,
success: function(result,testStatus){
},
error:function(xhr,errorMessage,e){
}
})
例子:
function register(){
var $mobile = $("#mobile").val();
$.ajax({
url:"mobileServlet",
type:"post",
data:"mobile="+$mobile,
success:function(result,testStatus){
if(result == "true"){
alert("号码已存在!")
}else{
alert("注册成功!")
}
},
error:function(xhr,errorMessage,e){
alert("系统异常!")
}
})
}
get格式:
$.get( (严格要求参数顺序)
服务器地址,
请求数据,
function(result){
},
y预期返回值类型(String/xml/json)
);
post格式:
$.post( (严格要求参数顺序)
服务器地址,
请求数据,
function(result){
},
预期返回值类型(String/xml/json)
)
例子:
$.post(
"mobileServlet",
"mobile="+$mobile,
function(result){
if(result == "true"){
alert("号码已存在!")
}else{
alert("注册成功!")
}
},
"text"
)
load格式
直接把服务器的返回值 直接加载到$(xxx)所选着的元素中
$(xxx).load(
服务器地址,
请求数据
function可选
);
例子:
$("#tip").load(
"mobileServlet",
"mobile="+$mobile
)
<span id = 'tip'></span>
json格式:
$.getJSON(
服务器地址,
JSON格式的请求数据,
function(result){
}
);//返回值是json
如果客户端是getJSON,则服务端需要以json格式返回数据
js需要通过eval()函数 将返回值转为一个js能识别的json对象
例:
前端:
function testjson(){
$.getJSON(
"JsonServlet",
{"name":"yuan","age":321},
function(result){
//js需要通过eval()函数 将返回值转为一个js能识别的json对象
var jsonStudent = eval(result);
$.each(jsonStudent,function(i,element){
alert(this.name +"--"+this.age);
});
}
);
后端:
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
Student stu = new Student(12,"dgg");
json.put("stu", stu);
out.print(json);//返回json对象
out.close();