首先写一个有AJAX的页面
前端创建一个AJAX.jsp
1,导包(容易忽视)
<script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js">
</script>
2,写表单
用户名:<input type="text" id="name" name="name" onblur="a1()">
<span id="userinfo"></span><br>
3,写Ajax(重点,开始写有很多的错误)
<script>
function a1(){
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/servlet/AJAX",
data:{'name':$("#name").val()},/*这里的data不要写成date*/
dataType:"json",/*这里是后端返回的格式,需要在前端设置。*/
success:function (data){/*要进入success函数的条件是,前面的属性都要成功或者符合,否者会进入error*/
if(data.nameflag=="ok"){
$('#userinfo').css("color","blue");
}else{
$("#userinfo").css("color","red");
}
$("#userinfo").html(data.nameflag);
},
error: function (nameflag){
console.log(nameflag);
}
});
}
</script>
后端写一个Servlet
1,导包(注意Maven中配完了,Tomcat中也要配置)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
2,注册servlet
<servlet>
<servlet-name>Ajaxcontroller</servlet-name>
<servlet-class>com.Google.controller.Ajaxcontroller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ajaxcontroller</servlet-name>
<url-pattern>/servlet/AJAX</url-pattern>
</servlet-mapping>
3,写Servlet
resp.setContentType("application/javascript;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
System.out.println("name"+name);
String password = req.getParameter("password");
HashMap<String, String> resultMap = new HashMap<String,String>();//重点,这个Map很重要
if(name!=null){
if(name.equals("123")){
resultMap.put("nameflag","ok");
}else{
resultMap.put("nameflag","输入用户名有误!");
}
}
resp.setContentType("application/json");//设置返回的数据为json格式
PrintWriter writer = resp.getWriter();//应为是响应(resp)所以这里的流是写到服务器中去
writer.flush();
writer.write(JSONArray.toJSONString(resultMap));//注意这里要写Write不要写print
writer.close();
}
这个简单的项目我编写和排错用了大概五小时,过程虽然痛苦,但是真的是学到了很多