依赖
首先要引入 jquery.js
文件
ajax完整写法
$.ajax({
url:'/add',//请求的url
type:'POST', //请求方式,GET或POST
async:true, //可省略,默认为true,异步;false:同步
data:{ //发送服务器的数据
name:'李雷',
age:25
},
timeout:5000, //超时时间,可省略
dataType:'json', //返回的数据格式:json/xml/html/script/jsonp/text
beforeSend:function(xhr){ //发请求前执行该方法,可省略
console.log(xhr)
console.log('发送前')
},
success:function(data,textStatus,jqXHR){ //statusCode是2xx 或 304时,执行该函数
console.log(data)
console.log(textStatus)
console.log(jqXHR)
},
error:function(xhr,textStatus){ //statusCode是 2xx 或 304 以外的值时,执行该函数
console.log('错误')
console.log(xhr)
console.log(textStatus)
},
complete:function(){//请求完成后执行该函数,可省略
console.log('结束')
}
})
更多参数详细解释,参见:
常用写法
$.ajax({
url:'/add',//请求的url
type:'POST', //请求方式,GET或POST
data:{ //发送服务器的数据
name:'李雷',
age:25
},
dataType:'json', //返回的数据格式:json/xml/html/script/jsonp/text
success:function(data,textStatus,jqXHR){ //statusCode是2xx 或 304时,执行该函数
console.log(data)
console.log(textStatus)
console.log(jqXHR)
},
error:function(xhr,textStatus){ //statusCode是 2xx 或 304 以外的值时,执行该函数
console.log('错误')
console.log(xhr)
console.log(textStatus)
}
})
get简化写法
格式:
$.get(URL,callback);
例子
$.get("/query",function(data,status){
console.log("数据: " , data , ",状态: " + status);
});
post简化写法
格式:
$.post(URL,data,callback);
例子
$.post("/add",
{
name:"李雷",
age:20
},
function(data,status){
console.log("数据: " , data , ",状态: " + status);
}
);
例子
首先要引入jquery.js文件
js部分
function doSubmit(){
alert(1);//目的:判断该函数是否能正确的执行
var name=$("#username").val();//jquery根据id值获取该控件的value值,#后面都是id值
alert(name);
$.ajax({
url:'reg/check',
type:'POST', //GET
data:{
'name':name
},
dataType:'json', //返回的数据格式:json/xml/html/script/jsonp/text
success:function(data,textStatus,jqXHR){
alert(data); //如果不做处理,弹出的是object,原因就是json是对象
alert(JSON.stringify(data));//将json对象转换为字符串
if(data.code==1){//检验成功,查无此用户
document.myform.submit();
}else{
alert('该用户已经存在');
}
},
error:function(xhr,textStatus){
alert("对不起,发生错误!");
}
})
}
html的部分
<form name="myform" action="reg/doReg" method="post">
用户名:<input name="username" id="username"><br/>
密码:<input name="password" id="password"><br/>
<input type="button" value="注册" onclick="doSubmit()">
</form>
传统方式:点击“注册”,提交表单,整个页面要刷新
ajax方式:点击“注册”,异步提交,判断用户名是否存在,如果存在就给出提示