ajax在表单中常用,一般都是使用post方法,ajax请求:前台提交数据→后台查询数据→返回给前台
下面以post方法为例上代码:
<form action="login" method="post"> ???????用户名:<input type="text" onblur="checkUser()"> ???????<span></span> ???????密码:<input type="password"> ???????<button>登录</button></form>
javascript:
<script> ???????function checkUser(){ ???????????var userName=document.getElementsByTagName("input")[0].value; ???????????var mark=document.getElementsByTagName("span")[0]; ???????????var xhr=""; ???????????if(window.XMLHttpRequest){ ???????????????xhr=new XMLHttpRequest(); ???????????}else if(window.ActiveXObject){ ???????????????xhr=new ActiveXObject(); ???????????}//处理浏览器兼容 ???????????xhr.open("post","login",true);//请求的方式、地址、异步 ???????????xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");//post请求设置请求头 ???????????xhr.send("userName="+userName); ???????????xhr.onreadystatechange=function(){ ???????????????//接收后台传回的数据 ?更新页面 ???????????????if(xhr.readyState==200 && xhr.status==4){ ???????????????????if(response==0){ ???????????????????????mark.innerText="已注册请登录" ???????????????????}else if(response==1){ ???????????????????????mark.innerText="用户名不存在请注册" ???????????????????} ???????????????} ???????????} ???????}</script>
服务器拦截并响应:
app.post("login",function(req,res){ ?//拦截地址 ?设置回调函数 ???let userName=req.body.userName;//获取到用户输入的用户名 ???let sqlStr="select * from t_user where u_name=?"//查询数据库用户名 ???database.dbconnect(sqlStr,[],function(err,data){ ???????if(data.length>0){ ??//判断用户名是否存在,做出相应响应 ???????????res.send("0")//用户名存在返回0 ???????}else{ ???????????res.send("1")//用户名不存在返回1 ???????} ???})})
以上为今天所有分享,欢迎评论赐教;
如需了解更多,请进入知了堂社区:http://www.zhiliaotang.com/portal.php;
ajax ?提交表单 ?原生js
原文地址:http://www.cnblogs.com/hddhhanzi/p/7674926.html