jQuery对ajax操作进行了很好的封装,下面对常见的$.ajax()方法参数进行说明
url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。
type: 要求为String类型的参数,请求方式(post或get)默认为get。注意其他HTTP请求方法,例如put和delete也可以使用,但仅部分浏览器支持。在支持RESTful时,该参数类型很重要。
async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。
beforeSend:要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参数。
success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。
(1)由服务器返回,并根据dataType参数进行处理后的数据。
(2)描述状态的字符串。
这里举一个在项目中用到的例子:
function submit()
{
$("#verify_code_error").text("");
$("#admin_code_error").text("");
$("#password_error").text("");
var adminCode = $("#adminCode").val();
var password = $("#password").val();
var verifyCode = $("#verifyCode").val();
if(verifyCode == null || verifyCode == "")
{
$("#verify_code_error").text("验证码为空");
return;
}
if(adminCode == null || adminCode == "")
{
$("#admin_code_error").text("用户名不能为空");
return;
}
if(password == null || password == "")
{
$("#password_error").text("密码不能为空");
return;
}
$.ajax({
url:"/20150725/login/login/" + verifyCode,
type:"get",
beforeSend:
function(xhr)
{
xhr.setRequestHeader("adminCode", adminCode);
xhr.setRequestHeader("password", password);
},
success:
function(map)
{
if(map.flag == false)
{
if(map.msgLocation == 0)
{
$("#verify_code_error").text(map.msg);
}
else if(map.msgLocation == 1)
{
$("#admin_code_error").text(map.msg);
}
else
{
$("#password_error").text(map.msg);
}
}
else
{
window.location = "/20150725/login/toindex";
}
}
});
}