更完整的写法
$.ajax({
url:'/comm/test1.php',//请求的url
type:'POST', //请求方式,GET或POST
async:true, //可省略,默认为true,异步;false:同步
data:{
name:'yang',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){//成功时执行该函数
console.log(data)
console.log(textStatus)
console.log(jqXHR)
},
error:function(xhr,textStatus){//错误时执行该函数
console.log('错误')
console.log(xhr)
console.log(textStatus)
},
complete:function(){//可省略
console.log('结束')
}
})前端完整的写法
首先要引入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的部分
注册<br/> 传统:点击“注册”,提交表单,整个页面要刷新<br/> ajax:点击“注册”,异步提交,判断用户名是否存在,如果存在就给出提示<br/> <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>